图片审核增强版SDK及接入指南

图片审核增强版支持SDK方式调用和原生HTTPS方式调用。推荐您使用SDK接入,可免去签名验证以及Body格式构建等细节步骤。本文介绍图片审核增强版接入的方式。

步骤一:开通服务

访问开通服务页面,开通图片审核增强版服务。

开通图片审核增强版服务后,默认付费方式是按量后付费,且按照实际用量结算当日费用,不调用服务不收费。接口接入使用后系统会按使用量自动出账,具体信息,请参见计费说明您也可以购买按量抵扣资源包,资源包相较于后付费存在一定阶梯折扣,适合使用量级可预期和较大的用户。

步骤二:创建RAM用户并授权

在集成SDK之前,您需要创建一个用于调用SDK的用户身份,获取身份关联的OpenAPI访问凭据,并授予访问云上资源的访问权限。本文创建RAM用户,获取访问凭据为AccessKey,并授予调用图片审核增强版服务的权限。更多信息,请参见集成SDK

  1. 使用阿里云账号(主账号)或具有管理权限的RAM用户登录RAM控制台

  2. 创建RAM用户,勾选OpenAPI调用访问,并记录下RAM用户生成的AccessKey。具体操作,请参见创建RAM用户

  3. RAM用户授权系统策略权限:AliyunYundunGreenWebFullAccess。具体操作,请参见RAM用户授权

步骤三:安装并接入SDK

目前支持的接入地域如下:

地域

外网接入地址

内网接入地址

华东2(上海)

green-cip.cn-shanghai.aliyuncs.com

green-cip-vpc.cn-shanghai.aliyuncs.com

华东1(杭州)

green-cip.cn-hangzhou.aliyuncs.com

green-cip-vpc.cn-hangzhou.aliyuncs.com

华北2(北京)

green-cip.cn-beijing.aliyuncs.com

green-cip-vpc.cn-beijing.aliyuncs.com

华南1(深圳)

green-cip.cn-shenzhen.aliyuncs.com

green-cip-vpc.cn-shenzhen.aliyuncs.com

西南1(成都)

green-cip.cn-chengdu.aliyuncs.com

暂无

新加坡

green-cip.ap-southeast-1.aliyuncs.com

green-cip-vpc.ap-southeast-1.aliyuncs.com

美国(弗吉尼亚)

green-cip.us-east-1.aliyuncs.com

green-cip-vpc.us-east-1.aliyuncs.com

美国(硅谷)

green-cip.us-west-1.aliyuncs.com

暂无

伦敦

green-cip.eu-west-1.aliyuncs.com

暂无

说明

如果需要其他语言的SDK示例代码,您可以通过OpenAPI开发者门户在线调试工具调试API接口,该工具会自动生成相应APISDK调用示例代码。

阿里云SDK代码通过定义ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET环境变量来创建默认的访问凭证。调用接口时,程序直接访问凭证,读取您的访问密钥(即AccessKey)并自动完成鉴权。您在接入SDK代码示例之前,请先配置环境变量。具体操作,请参见身份验证配置

API接口字段说明请参考图片审核增强版同步检测API图片审核增强版异步检测API

Java SDK

支持Java 1.8及以上版本。

原始代码,请参见Java SDK源码或者Java SDK源码(OSS路径)

支持以下三种类型的图片检测。

对公网可访问图片进行检测

使用场景

当需要审核的图片可通过公网链接访问时,图片审核增强版服务可通过图片URL获取文件后进行审核。

  1. pom.xml中添加如下依赖安装Java SDK,即可以在Maven工程中使用SDK。

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>green20220302</artifactId>
      <version>2.19.1</version>
    </dependency>
  2. 接入Java SDK。

    • 同步接口接入示例

      import com.alibaba.fastjson.JSON;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.ImageModerationRequest;
      import com.aliyun.green20220302.models.ImageModerationResponse;
      import com.aliyun.green20220302.models.ImageModerationResponseBody;
      import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyData;
      import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyDataResult;
      import com.aliyun.teaopenapi.models.Config;
      import com.aliyun.teautil.models.RuntimeOptions;
      
      import java.util.HashMap;
      import java.util.List;
      import java.util.Map;
      import java.util.UUID;
      
      public class ImageUrlDemo {
          /**
           * 创建请求客户端
           *
           * @param accessKeyId
           * @param accessKeySecret
           * @param endpoint
           * @return
           * @throws Exception
           */
          public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              Config config = new Config();
              config.setAccessKeyId(accessKeyId);
              config.setAccessKeySecret(accessKeySecret);
              // 设置http代理。
              //config.setHttpProxy("http://10.10.xx.xx:xxxx");
              // 设置https代理。
              //config.setHttpsProxy("https://10.10.xx.xx:xxxx");
              // 接入区域和地址请根据实际情况修改
            	// 接入地址列表:https://help.aliyun.com/document_detail/467828.html?#section-uib-qkw-0c8
              config.setEndpoint(endpoint);
              return new Client(config);
          }
      
          public static ImageModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              //注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
              Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
              // 创建RuntimeObject实例并设置运行参数
              RuntimeOptions runtime = new RuntimeOptions();
      
              // 检测参数构造。
              Map<String, String> serviceParameters = new HashMap<>();
              //公网可访问的URL。
              serviceParameters.put("imageUrl", "https://img.alicdn.com/tfs/xxxxxxxxxx001.png");
              //待检测数据唯一标识
              serviceParameters.put("dataId", UUID.randomUUID().toString());
      
              ImageModerationRequest request = new ImageModerationRequest();
              // 图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
            	// 支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
              request.setService("baselineCheck");
              request.setServiceParameters(JSON.toJSONString(serviceParameters));
      
              ImageModerationResponse response = null;
              try {
                  response = client.imageModerationWithOptions(request, runtime);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return response;
          }
      
          public static void main(String[] args) throws Exception {
              /**
               * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
               * 常见获取环境变量方式:
               * 方式一:
               *     获取RAM用户AccessKey ID:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     获取RAM用户AccessKey Secret:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * 方式二:
               *     获取RAM用户AccessKey ID:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     获取RAM用户AccessKey Secret:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              String accessKeyId = "建议从环境变量中获取RAM用户AccessKey ID";
              String accessKeySecret = "建议从环境变量中获取RAM用户AccessKey Secret";
              // 接入区域和地址请根据实际情况修改。
              ImageModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-shanghai.aliyuncs.com");
              try {
                  // 自动路由。
                  if (response != null) {
                      //区域切换到cn-beijing。
                      if (500 == response.getStatusCode() || (response.getBody() != null && 500 == (response.getBody().getCode()))) {
                          // 接入区域和地址请根据实际情况修改。
                          response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-beijing.aliyuncs.com");
                      }
                  }
                  // 打印检测结果。
                  if (response != null) {
                      if (response.getStatusCode() == 200) {
                          ImageModerationResponseBody body = response.getBody();
                          System.out.println("requestId=" + body.getRequestId());
                          System.out.println("code=" + body.getCode());
                          System.out.println("msg=" + body.getMsg());
                          if (body.getCode() == 200) {
                              ImageModerationResponseBodyData data = body.getData();
                              System.out.println("dataId=" + data.getDataId());
                              List<ImageModerationResponseBodyDataResult> results = data.getResult();
                              for (ImageModerationResponseBodyDataResult result : results) {
                                  System.out.println("label=" + result.getLabel());
                                  System.out.println("confidence=" + result.getConfidence());
                              }
                          } else {
                              System.out.println("image moderation not success. code:" + body.getCode());
                          }
                      } else {
                          System.out.println("response not success. status:" + response.getStatusCode());
                      }
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }
    • 异步接口接入示例

      提交异步图片检测任务

      import com.alibaba.fastjson.JSON;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.ImageAsyncModerationRequest;
      import com.aliyun.green20220302.models.ImageAsyncModerationResponse;
      import com.aliyun.green20220302.models.ImageAsyncModerationResponseBody;
      import com.aliyun.teaopenapi.models.Config;
      import com.aliyun.teautil.models.RuntimeOptions;
      
      import java.util.HashMap;
      import java.util.Map;
      import java.util.UUID;
      
      public class ImageAsyncModerationDemo {
      
      
          public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              Config config = new Config();
              config.setAccessKeyId(accessKeyId);
              config.setAccessKeySecret(accessKeySecret);
              config.setEndpoint(endpoint);
              return new Client(config);
          }
      
          public static ImageAsyncModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String
                  endpoint) throws Exception {
              Client client = createClient(accessKeyId, accessKeySecret, endpoint);
              RuntimeOptions runtime = new RuntimeOptions();
              Map<String, String> serviceParameters = new HashMap<>();
              serviceParameters.put("imageUrl", "https://img.alicdn.com/tfs/xxxxxxxxxx001.png");
              serviceParameters.put("dataId", UUID.randomUUID().toString());
              ImageAsyncModerationRequest imageAsyncModerationRequest = new ImageAsyncModerationRequest();
              imageAsyncModerationRequest.setService("baselineCheck");
              imageAsyncModerationRequest.setServiceParameters(JSON.toJSONString(serviceParameters));
              ImageAsyncModerationResponse response = null;
              try {
                  response = client.imageAsyncModerationWithOptions(imageAsyncModerationRequest, runtime);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return response;
          }
      
          public static void main(String[] args) throws Exception {
              String accessKeyId = "建议从环境变量中获取RAM用户AccessKey ID";
              String accessKeySecret = "建议从环境变量中获取RAM用户AccessKey Secret";
              ImageAsyncModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-shanghai.aliyuncs.com");
              if (response != null) {
                  if (response.getStatusCode() == 200) {
                      ImageAsyncModerationResponseBody body = response.getBody();
                      System.out.println("requestId=" + body.getRequestId());
                      System.out.println("code=" + body.getCode());
                      System.out.println("msg=" + body.getMsg());
                      if (body.getCode() == 200) {
                          ImageAsyncModerationResponseBody.ImageAsyncModerationResponseBodyData data = body.getData();
                          System.out.println("dataId=" + data.getDataId());
                          System.out.println("requestId = [" + data.getReqId() + "]");
                      } else {
                          System.out.println("image asyncmoderation not success. code:" + body.getCode());
                      }
                  } else {
                      System.out.println("response not success. status:" + response.getStatusCode());
                  }
              }
      
          }
      
      }
      

      获取异步检测结果

      import com.alibaba.fastjson.JSON;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.*;
      import com.aliyun.teaopenapi.models.Config;
      
      public class DescribeImageModerationResult {
          public static void main(String[] args) throws Exception {
              Config config = new Config();
              /**
               * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
               * 常见获取环境变量方式:
               * 方式一:
               *     获取RAM用户AccessKey ID:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     获取RAM用户AccessKey Secret:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * 方式二:
               *     获取RAM用户AccessKey ID:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     获取RAM用户AccessKey Secret:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              config.setAccessKeyId("推荐从环境变量获取AccessKey ID");
              config.setAccessKeySecret("推荐从环境变量获取AccessKey Secret");
              //接入区域和地址请根据实际情况修改
              config.setRegionId("cn-shanghai");
              config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
              //连接时超时时间,单位毫秒(ms)。
              config.setReadTimeout(6000);
              //读取时超时时间,单位毫秒(ms)。
              config.setConnectTimeout(3000);
      
              Client client = new Client(config);
              DescribeImageModerationResultRequest describeImageModerationResultRequest = new DescribeImageModerationResultRequest();
              // 提交任务时返回的reqId
              describeImageModerationResultRequest.setReqId("1BB12784-FDDE-515D-AFE4-C5054F9F9269");
      
              try {
                  DescribeImageModerationResultResponse response = client.describeImageModerationResult(describeImageModerationResultRequest);
                  if (response.getStatusCode() == 200) {
                      DescribeImageModerationResultResponseBody result = response.getBody();
                      System.out.println("requestId=" + result.getRequestId());
                      System.out.println("code=" + result.getCode());
                      System.out.println("msg=" + result.getMsg());
                      if (200 == result.getCode()) {
                          DescribeImageModerationResultResponseBody.DescribeImageModerationResultResponseBodyData data = result.getData();
                          System.out.println("data = " + JSON.toJSONString(data));
                      } else {
                          System.out.println("image async moderation result not success. code:" + result.getCode());
                      }
                  } else {
                      System.out.println("response not success. status:" + response.getStatusCode());
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }
      
    • ervice同步接口接入示例

      import com.alibaba.fastjson.JSON;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.ImageBatchModerationRequest;
      import com.aliyun.green20220302.models.ImageBatchModerationResponse;
      import com.aliyun.green20220302.models.ImageBatchModerationResponseBody;
      import com.aliyun.teaopenapi.models.Config;
      import com.aliyun.teautil.models.RuntimeOptions;
      
      import java.util.HashMap;
      import java.util.List;
      import java.util.Map;
      import java.util.UUID;
      
      public class Demo {
      
      
          public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              Config config = new Config();
              config.setAccessKeyId(accessKeyId);
              config.setAccessKeySecret(accessKeySecret);
              config.setEndpoint(endpoint);
              return new Client(config);
          }
      
          public static ImageBatchModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String
                  endpoint) throws Exception {
              Client client = createClient(accessKeyId, accessKeySecret, endpoint);
              RuntimeOptions runtime = new RuntimeOptions();
              Map<String, String> serviceParameters = new HashMap<>();
              serviceParameters.put("imageUrl", "https://img.alicdn.com/tfs/xxxxxxxxxx001.png");
              serviceParameters.put("dataId", UUID.randomUUID().toString());
              ImageBatchModerationRequest imageBatchModerationRequest = new ImageBatchModerationRequest();
              imageBatchModerationRequest.setService("baselineCheck,baselineCheck_pro");
              imageBatchModerationRequest.setServiceParameters(JSON.toJSONString(serviceParameters));
              ImageBatchModerationResponse response = null;
              try {
                  response = client.imageBatchModerationWithOptions(imageBatchModerationRequest, runtime);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return response;
          }
      
          public static void main(String[] args) throws Exception {
              String accessKeyId = "建议从环境变量中获取RAM用户AccessKey ID";
              String accessKeySecret = "建议从环境变量中获取RAM用户AccessKey Secret";
              ImageBatchModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-shanghai.aliyuncs.com");
              if (response != null) {
                  if (response.getStatusCode() == 200) {
                      ImageBatchModerationResponseBody body = response.getBody();
                      System.out.println("requestId=" + body.getRequestId());
                      System.out.println("code=" + body.getCode());
                      System.out.println("msg=" + body.getMsg());
                      if (body.getCode() == 200) {
                          ImageBatchModerationResponseBody.ImageBatchModerationResponseBodyData data = body.getData();
                          System.out.println("dataId=" + data.getDataId());
                          List<ImageBatchModerationResponseBody.ImageBatchModerationResponseBodyDataResult> results = data.getResult();
                          for (ImageBatchModerationResponseBody.ImageBatchModerationResponseBodyDataResult result : results) {
                              System.out.println("label=" + result.getLabel());
                              System.out.println("confidence=" + result.getConfidence());
                          }
                      } else {
                          System.out.println("image moderation not success. code:" + body.getCode());
                      }
                  } else {
                      System.out.println("response not success. status:" + response.getStatusCode());
                  }
              }
      
          }
      
      }
      

对本地图片进行检测

使用场景

当您需要审核的图片在本地机器且无公网访问链接,您可以将图片上传到内容安全提供的对象存储OSS Bucket中,图片审核增强版服务可直接访问对象存储OSS,获取到图片内容后进行审核。

  1. 安装Java SDK。

    安装内容检测SDK:

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>green20220302</artifactId>
      <version>2.19.1</version>
    </dependency>

    安装OSS SDK:

    <dependency>
      <groupId>com.aliyun.oss</groupId>
      <artifactId>aliyun-sdk-oss</artifactId>
      <version>3.16.3</version>
    </dependency>
  2. 接入Java SDK。

    • 同步接口接入示例

      import com.alibaba.fastjson.JSON;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.DescribeUploadTokenResponse;
      import com.aliyun.green20220302.models.DescribeUploadTokenResponseBody;
      import com.aliyun.green20220302.models.ImageModerationRequest;
      import com.aliyun.green20220302.models.ImageModerationResponse;
      import com.aliyun.green20220302.models.ImageModerationResponseBody;
      import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyData;
      import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyDataResult;
      import com.aliyun.oss.OSS;
      import com.aliyun.oss.OSSClientBuilder;
      import com.aliyun.oss.model.PutObjectRequest;
      import com.aliyun.teaopenapi.models.Config;
      import com.aliyun.teautil.models.RuntimeOptions;
      
      import java.io.File;
      import java.util.HashMap;
      import java.util.List;
      import java.util.Map;
      import java.util.UUID;
      
      public class ScanLocalImage {
      
          //服务是否部署在vpc上
          public static boolean isVPC = false;
      
          //文件上传token endpoint->token
          public static Map<String, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData> tokenMap = new HashMap<>();
      
          //上传文件请求客户端 
          public static OSS ossClient = null;
      
          /**
           * 创建请求客户端
           *
           * @param accessKeyId
           * @param accessKeySecret
           * @param endpoint
           * @return
           * @throws Exception
           */
          public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              Config config = new Config();
              config.setAccessKeyId(accessKeyId);
              config.setAccessKeySecret(accessKeySecret);
              // 接入区域和地址请根据实际情况修改
              config.setEndpoint(endpoint);
              return new Client(config);
          }
      
          /**
           * 创建上传文件请求客户端
           *
           * @param tokenData
           * @param isVPC
           */
          public static void getOssClient(DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData, boolean isVPC) {
              //注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
              if (isVPC) {
                  ossClient = new OSSClientBuilder().build(tokenData.ossInternalEndPoint, tokenData.getAccessKeyId(), tokenData.getAccessKeySecret(), tokenData.getSecurityToken());
              } else {
                  ossClient = new OSSClientBuilder().build(tokenData.ossInternetEndPoint, tokenData.getAccessKeyId(), tokenData.getAccessKeySecret(), tokenData.getSecurityToken());
              }
          }
      
          /**
           * 上传文件
           *
           * @param filePath
           * @param tokenData
           * @return
           * @throws Exception
           */
          public static String uploadFile(String filePath, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData) throws Exception {
              String[] split = filePath.split("\\.");
              String objectName;
              if (split.length > 1) {
                  objectName = tokenData.getFileNamePrefix() + UUID.randomUUID() + "." + split[split.length - 1];
              } else {
                  objectName = tokenData.getFileNamePrefix() + UUID.randomUUID();
              }
              PutObjectRequest putObjectRequest = new PutObjectRequest(tokenData.getBucketName(), objectName, new File(filePath));
              ossClient.putObject(putObjectRequest);
              return objectName;
          }
      
          public static ImageModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              //注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
              Client client = createClient(accessKeyId, accessKeySecret, endpoint);
              RuntimeOptions runtime = new RuntimeOptions();
      
              //本地文件的完整路径,例如D:\localPath\exampleFile.png。
              String filePath = "D:\localPath\exampleFile.png";
              //获取文件上传token
              if (tokenMap.get(endpoint) == null || tokenMap.get(endpoint).expiration <= System.currentTimeMillis() / 1000) {
                  DescribeUploadTokenResponse tokenResponse = client.describeUploadToken();
                  tokenMap.put(endpoint,tokenResponse.getBody().getData());
              }
              //上传文件请求客户端
              getOssClient(tokenMap.get(endpoint), isVPC);
      
              //上传文件
              String objectName = uploadFile(filePath, tokenMap.get(endpoint));
      
              // 检测参数构造。
              Map<String, String> serviceParameters = new HashMap<>();
              //文件上传信息
              serviceParameters.put("ossBucketName", tokenMap.get(endpoint).getBucketName());
              serviceParameters.put("ossObjectName", objectName);
              serviceParameters.put("dataId", UUID.randomUUID().toString());
      
              ImageModerationRequest request = new ImageModerationRequest();
              // 图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
              request.setService("baselineCheck");
              request.setServiceParameters(JSON.toJSONString(serviceParameters));
      
              ImageModerationResponse response = null;
              try {
                  response = client.imageModerationWithOptions(request, runtime);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return response;
          }
      
          public static void main(String[] args) throws Exception {
              /**
               * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
               * 常见获取环境变量方式:
               * 方式一:
               *     获取RAM用户AccessKey ID:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     获取RAM用户AccessKey Secret:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * 方式二:
               *     获取RAM用户AccessKey ID:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     获取RAM用户AccessKey Secret:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              String accessKeyId = "建议从环境变量中获取RAM用户AccessKey ID";
              String accessKeySecret = "建议从环境变量中获取RAM用户AccessKey Secret";
              // 接入区域和地址请根据实际情况修改。
              ImageModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-shanghai.aliyuncs.com");
              try {
                  // 自动路由。
                  if (response != null) {
                      //区域切换到cn-beijing。
                      if (500 == response.getStatusCode() || (response.getBody() != null && 500 == (response.getBody().getCode()))) {
                          // 接入区域和地址请根据实际情况修改。
                          response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-beijing.aliyuncs.com");
                      }
                  }
                  // 打印检测结果。
                  if (response != null) {
                      if (response.getStatusCode() == 200) {
                          ImageModerationResponseBody body = response.getBody();
                          System.out.println("requestId=" + body.getRequestId());
                          System.out.println("code=" + body.getCode());
                          System.out.println("msg=" + body.getMsg());
                          if (body.getCode() == 200) {
                              ImageModerationResponseBodyData data = body.getData();
                              System.out.println("dataId=" + data.getDataId());
                              List<ImageModerationResponseBodyDataResult> results = data.getResult();
                              for (ImageModerationResponseBodyDataResult result : results) {
                                  System.out.println("label=" + result.getLabel());
                                  System.out.println("confidence=" + result.getConfidence());
                              }
                          } else {
                              System.out.println("image moderation not success. code:" + body.getCode());
                          }
                      } else {
                          System.out.println("response not success. status:" + response.getStatusCode());
                      }
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }
    • 异步接口接入示例

      提交异步图片检测任务

      import com.alibaba.fastjson.JSON;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.DescribeUploadTokenResponse;
      import com.aliyun.green20220302.models.DescribeUploadTokenResponseBody;
      import com.aliyun.green20220302.models.ImageAsyncModerationRequest;
      import com.aliyun.green20220302.models.ImageAsyncModerationResponse;
      import com.aliyun.green20220302.models.ImageAsyncModerationResponseBody;
      import com.aliyun.green20220302.models.ImageAsyncModerationResponseBody.ImageAsyncModerationResponseBodyData;
      import com.aliyun.oss.OSS;
      import com.aliyun.oss.OSSClientBuilder;
      import com.aliyun.oss.model.PutObjectRequest;
      import com.aliyun.teaopenapi.models.Config;
      import com.aliyun.teautil.models.RuntimeOptions;
      
      import java.io.File;
      import java.util.HashMap;
      import java.util.Map;
      import java.util.UUID;
      
      public class ImageAsyncModerationUploads {
      
          //服务是否部署在vpc上
          public static boolean isVPC = false;
      
          //文件上传token endpoint->token
          public static Map<String, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData> tokenMap = new HashMap<>();
      
          //上传文件请求客户端 
          public static OSS ossClient = null;
      
          /**
           * 创建请求客户端
           *
           * @param accessKeyId
           * @param accessKeySecret
           * @param endpoint
           * @return
           * @throws Exception
           */
          public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              Config config = new Config();
              config.setAccessKeyId(accessKeyId);
              config.setAccessKeySecret(accessKeySecret);
              // 接入区域和地址请根据实际情况修改
              config.setEndpoint(endpoint);
              return new Client(config);
          }
      
          /**
           * 创建上传文件请求客户端
           *
           * @param tokenData
           * @param isVPC
           */
          public static void getOssClient(DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData, boolean isVPC) {
              //注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
              if (isVPC) {
                  ossClient = new OSSClientBuilder().build(tokenData.ossInternalEndPoint, tokenData.getAccessKeyId(), tokenData.getAccessKeySecret(), tokenData.getSecurityToken());
              } else {
                  ossClient = new OSSClientBuilder().build(tokenData.ossInternetEndPoint, tokenData.getAccessKeyId(), tokenData.getAccessKeySecret(), tokenData.getSecurityToken());
              }
          }
      
          /**
           * 上传文件
           *
           * @param filePath
           * @param tokenData
           * @return
           * @throws Exception
           */
          public static String uploadFile(String filePath, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData) throws Exception {
              String[] split = filePath.split("\\.");
              String objectName;
              if (split.length > 1) {
                  objectName = tokenData.getFileNamePrefix() + UUID.randomUUID() + "." + split[split.length - 1];
              } else {
                  objectName = tokenData.getFileNamePrefix() + UUID.randomUUID();
              }
              PutObjectRequest putObjectRequest = new PutObjectRequest(tokenData.getBucketName(), objectName, new File(filePath));
              ossClient.putObject(putObjectRequest);
              return objectName;
          }
      
          public static ImageAsyncModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              //注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
              Client client = createClient(accessKeyId, accessKeySecret, endpoint);
              RuntimeOptions runtime = new RuntimeOptions();
      
              //本地文件的完整路径,例如D:\localPath\exampleFile.png。
              String filePath = "/Users/test/image/0544.jpg";
              //获取文件上传token
              if (tokenMap.get(endpoint) == null || tokenMap.get(endpoint).expiration <= System.currentTimeMillis() / 1000) {
                  DescribeUploadTokenResponse tokenResponse = client.describeUploadToken();
                  tokenMap.put(endpoint,tokenResponse.getBody().getData());
              }
              //上传文件请求客户端
              getOssClient(tokenMap.get(endpoint), isVPC);
      
              //上传文件
              String objectName = uploadFile(filePath, tokenMap.get(endpoint));
      
              // 检测参数构造。
              Map<String, String> serviceParameters = new HashMap<>();
              //文件上传信息
              serviceParameters.put("ossBucketName", tokenMap.get(endpoint).getBucketName());
              serviceParameters.put("ossObjectName", objectName);
              serviceParameters.put("dataId", UUID.randomUUID().toString());
      
              ImageAsyncModerationRequest request = new ImageAsyncModerationRequest();
              // 图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
              request.setService("baselineCheck");
              request.setServiceParameters(JSON.toJSONString(serviceParameters));
      
              ImageAsyncModerationResponse response = null;
              try {
                  response = client.imageAsyncModerationWithOptions(request, runtime);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return response;
          }
      
          public static void main(String[] args) throws Exception {
              /**
               * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
               * 常见获取环境变量方式:
               * 方式一:
               *     获取RAM用户AccessKey ID:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     获取RAM用户AccessKey Secret:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * 方式二:
               *     获取RAM用户AccessKey ID:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     获取RAM用户AccessKey Secret:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              String accessKeyId = "建议从环境变量中获取RAM用户AccessKey ID";
              String accessKeySecret = "建议从环境变量中获取RAM用户AccessKey Secret";
              // 接入区域和地址请根据实际情况修改。
              ImageAsyncModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-shanghai.aliyuncs.com");
              try {
                  // 自动路由。
                  if (response != null) {
                      //区域切换到cn-beijing。
                      if (500 == response.getStatusCode() || (response.getBody() != null && 500 == (response.getBody().getCode()))) {
                          // 接入区域和地址请根据实际情况修改。
                          response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-beijing.aliyuncs.com");
                      }
                  }
                  // 打印检测结果。
                  if (response != null) {
                      if (response.getStatusCode() == 200) {
                          ImageAsyncModerationResponseBody body = response.getBody();
                          System.out.println("requestId=" + body.getRequestId());
                          System.out.println("code=" + body.getCode());
                          System.out.println("msg=" + body.getMsg());
                          if (body.getCode() == 200) {
                              ImageAsyncModerationResponseBodyData data = body.getData();
                              System.out.println("dataId=" + data.getDataId());
                              System.out.println("reqId = [" + data.getReqId() + "]");
                          } else {
                              System.out.println("image async moderation not success. code:" + body.getCode());
                          }
                      } else {
                          System.out.println("response not success. status:" + response.getStatusCode());
                      }
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }

      获取异步图片检测结果

      import com.alibaba.fastjson.JSON;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.*;
      import com.aliyun.teaopenapi.models.Config;
      
      public class DescribeImageModerationResult {
          public static void main(String[] args) throws Exception {
              Config config = new Config();
              /**
               * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
               * 常见获取环境变量方式:
               * 方式一:
               *     获取RAM用户AccessKey ID:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     获取RAM用户AccessKey Secret:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * 方式二:
               *     获取RAM用户AccessKey ID:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     获取RAM用户AccessKey Secret:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              config.setAccessKeyId("推荐从环境变量获取AccessKey ID");
              config.setAccessKeySecret("推荐从环境变量获取AccessKey Secret");
              //接入区域和地址请根据实际情况修改
              config.setRegionId("cn-shanghai");
              config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
              //连接时超时时间,单位毫秒(ms)。
              config.setReadTimeout(6000);
              //读取时超时时间,单位毫秒(ms)。
              config.setConnectTimeout(3000);
      
              Client client = new Client(config);
              DescribeImageModerationResultRequest describeImageModerationResultRequest = new DescribeImageModerationResultRequest();
              // 提交任务时返回的reqId
              describeImageModerationResultRequest.setReqId("1BB12784-FDDE-515D-AFE4-C5054F9F9269");
      
              try {
                  DescribeImageModerationResultResponse response = client.describeImageModerationResult(describeImageModerationResultRequest);
                  if (response.getStatusCode() == 200) {
                      DescribeImageModerationResultResponseBody result = response.getBody();
                      System.out.println("requestId=" + result.getRequestId());
                      System.out.println("code=" + result.getCode());
                      System.out.println("msg=" + result.getMsg());
                      if (200 == result.getCode()) {
                          DescribeImageModerationResultResponseBody.DescribeImageModerationResultResponseBodyData data = result.getData();
                          System.out.println("data = " + JSON.toJSONString(data));
                      } else {
                          System.out.println("image async moderation result not success. code:" + result.getCode());
                      }
                  } else {
                      System.out.println("response not success. status:" + response.getStatusCode());
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }
      
    • service同步接口接入示例

      import com.alibaba.fastjson.JSON;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.DescribeUploadTokenResponse;
      import com.aliyun.green20220302.models.DescribeUploadTokenResponseBody;
      import com.aliyun.green20220302.models.ImageBatchModerationRequest;
      import com.aliyun.green20220302.models.ImageBatchModerationResponse;
      import com.aliyun.green20220302.models.ImageBatchModerationResponseBody;
      import com.aliyun.green20220302.models.ImageBatchModerationResponseBody.ImageBatchModerationResponseBodyData;
      import com.aliyun.green20220302.models.ImageBatchModerationResponseBody.ImageBatchModerationResponseBodyDataResult;
      import com.aliyun.oss.OSS;
      import com.aliyun.oss.OSSClientBuilder;
      import com.aliyun.oss.model.PutObjectRequest;
      import com.aliyun.teaopenapi.models.Config;
      import com.aliyun.teautil.models.RuntimeOptions;
      
      import java.io.File;
      import java.util.HashMap;
      import java.util.List;
      import java.util.Map;
      import java.util.UUID;
      
      public class ImageBatchModerationUploads {
      
          //服务是否部署在vpc上
          public static boolean isVPC = false;
      
          //文件上传token endpoint->token
          public static Map<String, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData> tokenMap = new HashMap<>();
      
          //上传文件请求客户端 
          public static OSS ossClient = null;
      
          /**
           * 创建请求客户端
           *
           * @param accessKeyId
           * @param accessKeySecret
           * @param endpoint
           * @return
           * @throws Exception
           */
          public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              Config config = new Config();
              config.setAccessKeyId(accessKeyId);
              config.setAccessKeySecret(accessKeySecret);
              // 接入区域和地址请根据实际情况修改
              config.setEndpoint(endpoint);
              return new Client(config);
          }
      
          /**
           * 创建上传文件请求客户端
           *
           * @param tokenData
           * @param isVPC
           */
          public static void getOssClient(DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData, boolean isVPC) {
              //注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
              if (isVPC) {
                  ossClient = new OSSClientBuilder().build(tokenData.ossInternalEndPoint, tokenData.getAccessKeyId(), tokenData.getAccessKeySecret(), tokenData.getSecurityToken());
              } else {
                  ossClient = new OSSClientBuilder().build(tokenData.ossInternetEndPoint, tokenData.getAccessKeyId(), tokenData.getAccessKeySecret(), tokenData.getSecurityToken());
              }
          }
      
          /**
           * 上传文件
           *
           * @param filePath
           * @param tokenData
           * @return
           * @throws Exception
           */
          public static String uploadFile(String filePath, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData) throws Exception {
              String[] split = filePath.split("\\.");
              String objectName;
              if (split.length > 1) {
                  objectName = tokenData.getFileNamePrefix() + UUID.randomUUID() + "." + split[split.length - 1];
              } else {
                  objectName = tokenData.getFileNamePrefix() + UUID.randomUUID();
              }
              PutObjectRequest putObjectRequest = new PutObjectRequest(tokenData.getBucketName(), objectName, new File(filePath));
              ossClient.putObject(putObjectRequest);
              return objectName;
          }
      
          public static ImageBatchModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              //注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
              Client client = createClient(accessKeyId, accessKeySecret, endpoint);
              RuntimeOptions runtime = new RuntimeOptions();
      
              //本地文件的完整路径,例如D:\localPath\exampleFile.png。
              String filePath = "/Users/test/image/0544.jpg";
              //获取文件上传token
              if (tokenMap.get(endpoint) == null || tokenMap.get(endpoint).expiration <= System.currentTimeMillis() / 1000) {
                  DescribeUploadTokenResponse tokenResponse = client.describeUploadToken();
                  tokenMap.put(endpoint,tokenResponse.getBody().getData());
              }
              //上传文件请求客户端
              getOssClient(tokenMap.get(endpoint), isVPC);
      
              //上传文件
              String objectName = uploadFile(filePath, tokenMap.get(endpoint));
      
              // 检测参数构造。
              Map<String, String> serviceParameters = new HashMap<>();
              //文件上传信息
              serviceParameters.put("ossBucketName", tokenMap.get(endpoint).getBucketName());
              serviceParameters.put("ossObjectName", objectName);
              serviceParameters.put("dataId", UUID.randomUUID().toString());
      
              ImageBatchModerationRequest request = new ImageBatchModerationRequest();
              // 图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
              request.setService("baselineCheck,baselineCheck_pro");
              request.setServiceParameters(JSON.toJSONString(serviceParameters));
      
              ImageBatchModerationResponse response = null;
              try {
                  response = client.imageBatchModerationWithOptions(request, runtime);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return response;
          }
      
          public static void main(String[] args) throws Exception {
              /**
               * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
               * 常见获取环境变量方式:
               * 方式一:
               *     获取RAM用户AccessKey ID:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     获取RAM用户AccessKey Secret:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * 方式二:
               *     获取RAM用户AccessKey ID:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     获取RAM用户AccessKey Secret:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              String accessKeyId = "建议从环境变量中获取RAM用户AccessKey ID";
              String accessKeySecret = "建议从环境变量中获取RAM用户AccessKey Secret";
              // 接入区域和地址请根据实际情况修改。
              ImageBatchModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-shanghai.aliyuncs.com");
              try {
                  // 自动路由。
                  if (response != null) {
                      //区域切换到cn-beijing。
                      if (500 == response.getStatusCode() || (response.getBody() != null && 500 == (response.getBody().getCode()))) {
                          // 接入区域和地址请根据实际情况修改。
                          response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-beijing.aliyuncs.com");
                      }
                  }
                  // 打印检测结果。
                  if (response != null) {
                      if (response.getStatusCode() == 200) {
                          ImageBatchModerationResponseBody body = response.getBody();
                          System.out.println("requestId=" + body.getRequestId());
                          System.out.println("code=" + body.getCode());
                          System.out.println("msg=" + body.getMsg());
                          if (body.getCode() == 200) {
                              ImageBatchModerationResponseBodyData data = body.getData();
                              System.out.println("data=" + JSON.toJSONString(data));
                          } else {
                              System.out.println("image batch moderation not success. code:" + body.getCode());
                          }
                      } else {
                          System.out.println("response not success. status:" + response.getStatusCode());
                      }
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }

OSS图片进行检测

使用场景

如果您需要审核的图片文件已经存储在阿里云对象存储OSS中,你可授权创建服务角色,允许内容安全服务访问对象存储OSS。图片审核增强版服务会通过服务角色获取到对象存储OSS的文件后进行审核。访问云资源访问授权页面创建服务角色。

  1. 使用阿里云账号(即主账号)访问云资源访问授权页面进行授权。

  2. pom.xml中添加如下依赖安装Java SDK,即可以在Maven工程中使用SDK。

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>green20220302</artifactId>
      <version>2.19.1</version>
    </dependency>
  3. 接入Java SDK。

    • 同步接口接入示例

      import com.alibaba.fastjson.JSON;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.ImageModerationRequest;
      import com.aliyun.green20220302.models.ImageModerationResponse;
      import com.aliyun.green20220302.models.ImageModerationResponseBody;
      import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyData;
      import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyDataResult;
      import com.aliyun.teaopenapi.models.Config;
      import com.aliyun.teautil.models.RuntimeOptions;
      
      import java.util.HashMap;
      import java.util.List;
      import java.util.Map;
      import java.util.UUID;
      
      public class OssScanDemo {
          /**
           * 创建请求客户端
           *
           * @param accessKeyId
           * @param accessKeySecret
           * @param endpoint
           * @return
           * @throws Exception
           */
          public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              Config config = new Config();
              config.setAccessKeyId(accessKeyId);
              config.setAccessKeySecret(accessKeySecret);
              // 设置http代理。
              // config.setHttpProxy("http://10.10.xx.xx:xxxx");
              // 设置https代理。
              // config.setHttpsProxy("https://10.10.xx.xx:xxxx");
              // 接入区域和地址请根据实际情况修改
              config.setEndpoint(endpoint);
              return new Client(config);
          }
      
          public static ImageModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              //注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
              Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
              // 创建RuntimeObject实例并设置运行参数
              RuntimeOptions runtime = new RuntimeOptions();
      
              // 检测参数构造。
              Map<String, String> serviceParameters = new HashMap<>();
              //待检测数据唯一标识
              serviceParameters.put("dataId", UUID.randomUUID().toString());
              // 待检测文件所在bucket的区域。 示例:cn-shanghai
              serviceParameters.put("ossRegionId", "cn-shanghai");
              // 待检测文件所在bucket名称。示例:bucket001
              serviceParameters.put("ossBucketName", "bucket001");
              // 待检测文件。 示例:image/001.jpg
              serviceParameters.put("ossObjectName", "image/001.jpg");
      
              ImageModerationRequest request = new ImageModerationRequest();
              // 图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
            	// 支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
              request.setService("baselineCheck");
              request.setServiceParameters(JSON.toJSONString(serviceParameters));
      
              ImageModerationResponse response = null;
              try {
                  response = client.imageModerationWithOptions(request, runtime);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return response;
          }
      
          public static void main(String[] args) throws Exception {
              /**
               * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
               * 常见获取环境变量方式:
               * 方式一:
               *     获取RAM用户AccessKey ID:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     获取RAM用户AccessKey Secret:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * 方式二:
               *     获取RAM用户AccessKey ID:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     获取RAM用户AccessKey Secret:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              String accessKeyId = "建议从环境变量中获取RAM用户AccessKey ID";
              String accessKeySecret = "建议从环境变量中获取RAM用户AccessKey Secret";
              // 接入区域和地址请根据实际情况修改。
              ImageModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-shanghai.aliyuncs.com");
              try {
                  // 自动路由。
                  if (response != null) {
                      //区域切换到cn-beijing。
                      if (500 == response.getStatusCode() || (response.getBody() != null && 500 == (response.getBody().getCode()))) {
                          // 接入区域和地址请根据实际情况修改。
                          response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-beijing.aliyuncs.com");
                      }
                  }
                  // 打印检测结果。
                  if (response != null) {
                      if (response.getStatusCode() == 200) {
                          ImageModerationResponseBody body = response.getBody();
                          System.out.println("requestId=" + body.getRequestId());
                          System.out.println("code=" + body.getCode());
                          System.out.println("msg=" + body.getMsg());
                          if (body.getCode() == 200) {
                              ImageModerationResponseBodyData data = body.getData();
                              System.out.println("dataId=" + data.getDataId());
                              List<ImageModerationResponseBodyDataResult> results = data.getResult();
                              for (ImageModerationResponseBodyDataResult result : results) {
                                  System.out.println("label=" + result.getLabel());
                                  System.out.println("confidence=" + result.getConfidence());
                              }
                          } else {
                              System.out.println("image moderation not success. code:" + body.getCode());
                          }
                      } else {
                          System.out.println("response not success. status:" + response.getStatusCode());
                      }
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }
    • 异步接口接入示例

      提交异步图片检测任务

      import com.alibaba.fastjson.JSON;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.ImageAsyncModerationRequest;
      import com.aliyun.green20220302.models.ImageAsyncModerationResponse;
      import com.aliyun.green20220302.models.ImageAsyncModerationResponseBody;
      import com.aliyun.teaopenapi.models.Config;
      import com.aliyun.teautil.models.RuntimeOptions;
      
      import java.util.HashMap;
      import java.util.Map;
      import java.util.UUID;
      
      public class ImageAsyncModerationDemo {
      
      
          public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              Config config = new Config();
              config.setAccessKeyId(accessKeyId);
              config.setAccessKeySecret(accessKeySecret);
              config.setEndpoint(endpoint);
              return new Client(config);
          }
      
          public static ImageAsyncModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String
                  endpoint) throws Exception {
              Client client = createClient(accessKeyId, accessKeySecret, endpoint);
              RuntimeOptions runtime = new RuntimeOptions();
              Map<String, String> serviceParameters = new HashMap<>();
              serviceParameters.put("dataId", UUID.randomUUID().toString());
              // 待检测文件所在bucket的区域。 示例:cn-shanghai
              serviceParameters.put("ossRegionId", "cn-shanghai");
              // 待检测文件所在bucket名称。示例:bucket001
              serviceParameters.put("ossBucketName", "bucket001");
              // 待检测文件。 示例:image/001.jpg
              serviceParameters.put("ossObjectName", "image/001.jpg");
              ImageAsyncModerationRequest imageAsyncModerationRequest = new ImageAsyncModerationRequest();
              imageAsyncModerationRequest.setService("baselineCheck");
              imageAsyncModerationRequest.setServiceParameters(JSON.toJSONString(serviceParameters));
              ImageAsyncModerationResponse response = null;
              try {
                  response = client.imageAsyncModerationWithOptions(imageAsyncModerationRequest, runtime);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return response;
          }
      
          public static void main(String[] args) throws Exception {
              String accessKeyId = "建议从环境变量中获取RAM用户AccessKey ID";
              String accessKeySecret = "建议从环境变量中获取RAM用户AccessKey Secret";
              ImageAsyncModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-shanghai.aliyuncs.com");
              if (response != null) {
                  if (response.getStatusCode() == 200) {
                      ImageAsyncModerationResponseBody body = response.getBody();
                      System.out.println("requestId=" + body.getRequestId());
                      System.out.println("code=" + body.getCode());
                      System.out.println("msg=" + body.getMsg());
                      if (body.getCode() == 200) {
                          ImageAsyncModerationResponseBody.ImageAsyncModerationResponseBodyData data = body.getData();
                          System.out.println("dataId=" + data.getDataId());
                          System.out.println("requestId = [" + data.getReqId() + "]");
                      } else {
                          System.out.println("image asyncmoderation not success. code:" + body.getCode());
                      }
                  } else {
                      System.out.println("response not success. status:" + response.getStatusCode());
                  }
              }
      
          }
      
      }
      

      获取异步图片检测结果

      import com.alibaba.fastjson.JSON;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.*;
      import com.aliyun.teaopenapi.models.Config;
      
      public class DescribeImageModerationResult {
          public static void main(String[] args) throws Exception {
              Config config = new Config();
              /**
               * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
               * 常见获取环境变量方式:
               * 方式一:
               *     获取RAM用户AccessKey ID:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     获取RAM用户AccessKey Secret:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * 方式二:
               *     获取RAM用户AccessKey ID:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     获取RAM用户AccessKey Secret:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              config.setAccessKeyId("推荐从环境变量获取AccessKey ID");
              config.setAccessKeySecret("推荐从环境变量获取AccessKey Secret");
              //接入区域和地址请根据实际情况修改
              config.setRegionId("cn-shanghai");
              config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
              //连接时超时时间,单位毫秒(ms)。
              config.setReadTimeout(6000);
              //读取时超时时间,单位毫秒(ms)。
              config.setConnectTimeout(3000);
      
              Client client = new Client(config);
              DescribeImageModerationResultRequest describeImageModerationResultRequest = new DescribeImageModerationResultRequest();
              // 提交任务时返回的reqId
              describeImageModerationResultRequest.setReqId("1BB12784-FDDE-515D-AFE4-C5054F9F9269");
      
              try {
                  DescribeImageModerationResultResponse response = client.describeImageModerationResult(describeImageModerationResultRequest);
                  if (response.getStatusCode() == 200) {
                      DescribeImageModerationResultResponseBody result = response.getBody();
                      System.out.println("requestId=" + result.getRequestId());
                      System.out.println("code=" + result.getCode());
                      System.out.println("msg=" + result.getMsg());
                      if (200 == result.getCode()) {
                          DescribeImageModerationResultResponseBody.DescribeImageModerationResultResponseBodyData data = result.getData();
                          System.out.println("data = " + JSON.toJSONString(data));
                      } else {
                          System.out.println("image async moderation result not success. code:" + result.getCode());
                      }
                  } else {
                      System.out.println("response not success. status:" + response.getStatusCode());
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }
      
    • service同步接口接入示例

      import com.alibaba.fastjson.JSON;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.ImageBatchModerationRequest;
      import com.aliyun.green20220302.models.ImageBatchModerationResponse;
      import com.aliyun.green20220302.models.ImageBatchModerationResponseBody;
      import com.aliyun.teaopenapi.models.Config;
      import com.aliyun.teautil.models.RuntimeOptions;
      
      import java.util.HashMap;
      import java.util.List;
      import java.util.Map;
      import java.util.UUID;
      
      public class Demo {
      
      
          public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              Config config = new Config();
              config.setAccessKeyId(accessKeyId);
              config.setAccessKeySecret(accessKeySecret);
              config.setEndpoint(endpoint);
              return new Client(config);
          }
      
          public static ImageBatchModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String
                  endpoint) throws Exception {
              Client client = createClient(accessKeyId, accessKeySecret, endpoint);
              RuntimeOptions runtime = new RuntimeOptions();
              Map<String, String> serviceParameters = new HashMap<>();
              // 待检测文件所在bucket的区域。 示例:cn-shanghai
              serviceParameters.put("ossRegionId", "cn-shanghai");
              // 待检测文件所在bucket名称。示例:bucket001
              serviceParameters.put("ossBucketName", "bucket001");
              // 待检测文件。 示例:image/001.jpg
              serviceParameters.put("ossObjectName", "image/001.jpg");
              serviceParameters.put("dataId", UUID.randomUUID().toString());
              ImageBatchModerationRequest imageBatchModerationRequest = new ImageBatchModerationRequest();
              imageBatchModerationRequest.setService("baselineCheck,baselineCheck_pro");
              imageBatchModerationRequest.setServiceParameters(JSON.toJSONString(serviceParameters));
              ImageBatchModerationResponse response = null;
              try {
                  response = client.imageBatchModerationWithOptions(imageBatchModerationRequest, runtime);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return response;
          }
      
          public static void main(String[] args) throws Exception {
              String accessKeyId = "建议从环境变量中获取RAM用户AccessKey ID";
              String accessKeySecret = "建议从环境变量中获取RAM用户AccessKey Secret";
              ImageBatchModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-shanghai.aliyuncs.com");
              if (response != null) {
                  if (response.getStatusCode() == 200) {
                      ImageBatchModerationResponseBody body = response.getBody();
                      System.out.println("requestId=" + body.getRequestId());
                      System.out.println("code=" + body.getCode());
                      System.out.println("msg=" + body.getMsg());
                      if (body.getCode() == 200) {
                          ImageBatchModerationResponseBody.ImageBatchModerationResponseBodyData data = body.getData();
                          System.out.println("dataId=" + data.getDataId());
                          List<ImageBatchModerationResponseBody.ImageBatchModerationResponseBodyDataResult> results = data.getResult();
                          for (ImageBatchModerationResponseBody.ImageBatchModerationResponseBodyDataResult result : results) {
                              System.out.println("label=" + result.getLabel());
                              System.out.println("confidence=" + result.getConfidence());
                          }
                      } else {
                          System.out.println("image moderation not success. code:" + body.getCode());
                      }
                  } else {
                      System.out.println("response not success. status:" + response.getStatusCode());
                  }
              }
      
          }
      
      }
      

Python SDK

支持Python 3.6及以上版本。

原始代码,请参见Python SDK源码

支持以下三种类型的图片检测。

对公网可访问图片进行检测

使用场景

当需要审核的图片可通过公网链接访问时,图片审核增强版服务可通过图片URL获取文件后进行审核。

  1. 执行如下命令引入相关依赖。

    pip install alibabacloud_green20220302==2.19.1
  2. 接入Python SDK。

    • 同步接口接入示例

      # coding=utf-8
      
      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      from alibabacloud_tea_util.client import Client as UtilClient
      from alibabacloud_tea_util import models as util_models
      import json
      import uuid
      
      
      def create_client(access_key_id, access_key_secret, endpoint):
          config = Config(
              access_key_id=access_key_id,
              access_key_secret=access_key_secret,
              # 设置http代理。
              # http_proxy='http://10.10.xx.xx:xxxx',
              # 设置https代理。
              # https_proxy='https://10.10.xx.xx:xxxx',
              # 接入区域和地址请根据实际情况修改。
              endpoint=endpoint
          )
          return Client(config)
      
      
      def invoke_function(access_key_id, access_key_secret, endpoint):
          # 注意:此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
          client = create_client(access_key_id, access_key_secret, endpoint)
          # 创建RuntimeObject实例并设置运行参数。
          runtime = util_models.RuntimeOptions()
      
          # 检测参数构造。
          service_parameters = {
              # 公网可访问的图片url
              'imageUrl': 'https://img.alicdn.com/tfs/xxxxxxxxxx001.png',
              # 数据唯一标识
              'dataId': str(uuid.uuid1())
          }
      
          image_moderation_request = models.ImageModerationRequest(
              # 图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
            	# 支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
              service='baselineCheck',
              service_parameters=json.dumps(service_parameters)
          )
      
          try:
              return client.image_moderation_with_options(image_moderation_request, runtime)
          except Exception as err:
              print(err)
      
      
      if __name__ == '__main__':
          # 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
          # 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
          # 常见获取环境变量方式:
          # 获取RAM用户AccessKey ID:os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
          # 获取RAM用户AccessKey Secret:os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
          access_key_id='建议从环境变量中获取RAM用户AccessKey ID'
          access_key_secret='建议从环境变量中获取RAM用户AccessKey Secret'
          # 接入区域和地址请根据实际情况修改。
          response = invoke_function(access_key_id, access_key_secret, 'green-cip.cn-shanghai.aliyuncs.com')
          # 自动路由。
          if response is not None:
              if UtilClient.equal_number(500,
                                         response.status_code) or (response.body is not None and 200 != response.body.code):
                  # 区域切换到cn-beijing。
                  response = invoke_function(access_key_id, access_key_secret, 'green-cip.cn-beijing.aliyuncs.com')
      
              if response.status_code == 200:
                  # 调用成功。
                  # 获取审核结果。
                  result = response.body
                  print('response success. result:{}'.format(result))
                  if result.code == 200:
                      result_data = result.data
                      print('result: {}'.format(result_data))
              else:
                  print('response not success. status:{} ,result:{}'.format(response.status_code, response))
      
    • 异步接口接入示例

      提交异步图片检测任务

      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      import json
      import uuid
      
      config = Config(
          access_key_id='推荐从环境变量获取AccessKey Id',
          access_key_secret='推荐从环境变量获取AccessKey Secret',
          # 连接时超时时间,单位毫秒(ms)。
          connect_timeout=3000,
          # 读取时超时时间,单位毫秒(ms)。
          read_timeout=6000,
          region_id='cn-shanghai',
          endpoint='green-cip.cn-shanghai.aliyuncs.com'
      )
      clt = Client(config)
      serviceParameters = {
          'imageUrl': 'https://www.aliyun.com/132.jpg',
          'dataId': str(uuid.uuid4()),
          'infoType': 'logoData'
      }
      ImageAsyncModerationRequest = models.ImageAsyncModerationRequest(
          # 检测类型: baselineCheck 通⽤基线检测
          service='baselineCheck',
          service_parameters=json.dumps(serviceParameters)
      )
      try:
          response = clt.image_async_moderation(ImageAsyncModerationRequest)
          if response.status_code == 200:
              body = response.body
              print('requestId:{}'.format(body.request_id))
              print('code:{}'.format(body.code))
              print('msg:{}'.format(body.msg))
              if body.code == 200:
                  data = body.data
                  print('reqId:{}'.format(data.req_id))
              else:
                  print('response not success. code:{},msg:{}'.format(body.code, body.msg))
          else:
              print('response not success. status:{},result:{}'.format(response.status_code, response))
      
      except Exception as err:
          print(err)
      

      获取异步图片检测结果

      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      
      config = Config(
          access_key_id='推荐从环境变量获取AccessKey Id',
          access_key_secret='推荐从环境变量获取AccessKey Secret',
          # 连接时超时时间,单位毫秒(ms)。
          connect_timeout=3000,
          # 读取时超时时间,单位毫秒(ms)。
          read_timeout=6000,
          region_id='cn-shanghai',
          endpoint='green-cip.cn-shanghai.aliyuncs.com'
      )
      clt = Client(config)
      
      DescribeImageModerationResultRequest = models.DescribeImageModerationResultRequest(
          req_id='64C35F30-FFB3-5312-96E1-04DC8D2AE19D'
      )
      try:
          response = clt.describe_image_moderation_result(DescribeImageModerationResultRequest)
          if response.status_code == 200:
              body = response.body
              print('requestId:{}'.format(body.request_id))
              print('code:{}'.format(body.code))
              print('msg:{}'.format(body.msg))
              if body.code == 200:
                  data = body.data
                  print(data.to_map())
                  print('dataId:{}'.format(data.data_id))
                  print('riskLevel:{}'.format(data.risk_level))
                  result = data.result[0]
                  print(result.to_map())
              else:
                  print('response not success. code:{},msg:{}'.format(body.code, body.msg))
          else:
              print('response not success. status:{},result:{}'.format(response.status_code, response))
      
      except Exception as err:
          print(err)
      
    • service同步接口接入示例

      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      from alibabacloud_tea_util import models as util_models
      import json
      import uuid
      
      
      def create_client(access_key_id, access_key_secret, endpoint):
          config = Config(
              access_key_id=access_key_id,
              access_key_secret=access_key_secret,
              endpoint=endpoint
          )
          return Client(config)
      
      
      def invoke_function(access_key_id, access_key_secret, endpoint):
          client = create_client(access_key_id, access_key_secret, endpoint)
          runtime = util_models.RuntimeOptions()
          service_parameters = {
              'imageUrl': 'http://www.aliyun.com/2c06373cj00s8j82k004ld000zk01bfc.jpg',
              'dataId': str(uuid.uuid1())
          }
          image_batchtion_request = models.ImageBatchModerationRequest(
              'baselineCheck,baselineCheck_pro',
              json.dumps(service_parameters)
      
          )
      
          try:
              return client.image_batch_moderation_with_options(image_batchtion_request, runtime)
          except Exception as err:
              print(err)
      
      
      if __name__ == '__main__':
          access_key_id = '建议从环境变量中获取RAM用户AccessKey ID'
          access_key_secret = '建议从环境变量中获取RAM用户AccessKey Secret'
          response = invoke_function(access_key_id, access_key_secret, 'green-cip.cn-shanghai.aliyuncs.com')
          print('response:{}', response)
      
          if response is not None:
              if response.status_code == 200:
                  result = response.body
                  print('response success. result:{}'.format(result))
                  if result.code == 200:
                      result_data = result.data
                      print('result: {}'.format(result_data))
              else:
                  print('response not success. status:{} ,result:{}'.format(response.status_code, response))
      

使用本地图片进行检测

使用场景

当您需要审核的图片在本地机器且无公网访问链接,您可以将图片上传到内容安全提供的对象存储OSS Bucket中,图片审核增强版服务可直接访问对象存储OSS,获取到图片内容后进行审核。

  1. 安装Python SDK。

    安装内容安全SDK:

    pip install alibabacloud_green20220302==2.19.1

    安装OSS SDK:

    pip install oss2
  2. 接入Python SDK。

    • 同步接口接入示例

      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      from alibabacloud_tea_util.client import Client as UtilClient
      from alibabacloud_tea_util import models as util_models
      import json
      import uuid
      import oss2
      import time
      
      # 服务是否部署在vpc上
      is_vpc = False
      # 文件上传token endpoint->token
      token_dict = dict()
      # 上传文件客户端
      bucket = None
      
      
      # 创建请求客户端
      def create_client(access_key_id, access_key_secret, endpoint):
          config = Config(
              access_key_id=access_key_id,
              access_key_secret=access_key_secret,
              # 设置http代理。
              # http_proxy='http://10.10.xx.xx:xxxx',
              # 设置https代理。
              # https_proxy='https://10.10.xx.xx:xxxx',
              # 接入区域和地址请根据实际情况修改。
              endpoint=endpoint
          )
          return Client(config)
      
      
      # 创建文件上传客户端
      def create_oss_bucket(is_vpc, upload_token):
          global token_dict
          global bucket
          auth = oss2.StsAuth(upload_token.access_key_id, upload_token.access_key_secret, upload_token.security_token)
      
          if (is_vpc):
              end_point = upload_token.oss_internal_end_point
          else:
              end_point = upload_token.oss_internet_end_point
          # 注意:此处实例化的bucket请尽可能重复使用,避免重复建立连接,提升检测性能。
          bucket = oss2.Bucket(auth, end_point, upload_token.bucket_name)
      
      # 上传文件
      def upload_file(file_name, upload_token):
          create_oss_bucket(is_vpc, upload_token)
          object_name = upload_token.file_name_prefix + str(uuid.uuid1()) + '.' + file_name.split('.')[-1]
          bucket.put_object_from_file(object_name, file_name)
          return object_name
      
      
      def invoke_function(access_key_id, access_key_secret, endpoint):
          # 注意:此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
          client = create_client(access_key_id, access_key_secret, endpoint)
          # 创建RuntimeObject实例并设置运行参数。
          runtime = util_models.RuntimeOptions()
      
          # 本地文件的完整路径,例如D:\localPath\exampleFile.png
          file_path = 'D:\localPath\exampleFile.png'
      
          # 获取文件上传token
          upload_token = token_dict.setdefault(endpoint, None)
          if (upload_token == None) or int(upload_token.expiration) <= int(time.time()):
              response = client.describe_upload_token()
              upload_token = response.body.data
              token_dict[endpoint] = upload_token
          # 上传文件
          object_name = upload_file(file_path, upload_token)
      
          # 检测参数构造。
          service_parameters = {
              # 待检测文件所在bucket名称。
              'ossBucketName': upload_token.bucket_name,
              # 待检测文件。
              'ossObjectName': object_name,
              # 数据唯一标识
              'dataId': str(uuid.uuid1())
          }
      
          image_moderation_request = models.ImageModerationRequest(
              # 图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
            	# 支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
              service='baselineCheck',
              service_parameters=json.dumps(service_parameters)
          )
      
          try:
              return client.image_moderation_with_options(image_moderation_request, runtime)
          except Exception as err:
              print(err)
      
      
      if __name__ == '__main__':
          # 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
          # 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
          # 常见获取环境变量方式:
          # 获取RAM用户AccessKey ID:os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
          # 获取RAM用户AccessKey Secret:os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
          access_key_id='建议从环境变量中获取RAM用户AccessKey ID'
          access_key_secret='建议从环境变量中获取RAM用户AccessKey Secret'
          # 接入区域和地址请根据实际情况修改。
          response = invoke_function(access_key_id, access_key_secret, 'green-cip.cn-shanghai.aliyuncs.com')
          # 自动路由。
          if response is not None:
              if UtilClient.equal_number(500,
                                         response.status_code) or (response.body is not None and 200 != response.body.code):
                  # 区域切换到cn-beijing。
                  response = invoke_function(access_key_id, access_key_secret, 'green-cip.cn-beijing.aliyuncs.com')
      
              if response.status_code == 200:
                  # 调用成功。
                  # 获取审核结果。
                  result = response.body
                  print('response success. result:{}'.format(result))
                  if result.code == 200:
                      result_data = result.data
                      print('result: {}'.format(result_data))
              else:
                  print('response not success. status:{} ,result:{}'.format(response.status_code, response))
      
    • 异步接口接入示例

      提交异步图片检测任务

      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      from alibabacloud_tea_util.client import Client as UtilClient
      from alibabacloud_tea_util import models as util_models
      import json
      import uuid
      import oss2
      import time
      
      # 服务是否部署在vpc上
      is_vpc = False
      # 文件上传token endpoint->token
      token_dict = dict()
      # 上传文件客户端
      bucket = None
      
      
      # 创建请求客户端
      def create_client(access_key_id, access_key_secret, endpoint):
          config = Config(
              access_key_id=access_key_id,
              access_key_secret=access_key_secret,
              # 设置http代理。
              # http_proxy='http://10.10.xx.xx:xxxx',
              # 设置https代理。
              # https_proxy='https://10.10.xx.xx:xxxx',
              # 接入区域和地址请根据实际情况修改。
              endpoint=endpoint
          )
          return Client(config)
      
      
      # 创建文件上传客户端
      def create_oss_bucket(is_vpc, upload_token):
          global token_dict
          global bucket
          auth = oss2.StsAuth(upload_token.access_key_id, upload_token.access_key_secret, upload_token.security_token)
      
          if (is_vpc):
              end_point = upload_token.oss_internal_end_point
          else:
              end_point = upload_token.oss_internet_end_point
          # 注意:此处实例化的bucket请尽可能重复使用,避免重复建立连接,提升检测性能。
          bucket = oss2.Bucket(auth, end_point, upload_token.bucket_name)
      
      
      # 上传文件
      def upload_file(file_name, upload_token):
          create_oss_bucket(is_vpc, upload_token)
          object_name = upload_token.file_name_prefix + str(uuid.uuid1()) + '.' + file_name.split('.')[-1]
          bucket.put_object_from_file(object_name, file_name)
          return object_name
      
      
      def invoke_function(access_key_id, access_key_secret, endpoint):
          # 注意:此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
          client = create_client(access_key_id, access_key_secret, endpoint)
          # 创建RuntimeObject实例并设置运行参数。
          runtime = util_models.RuntimeOptions()
      
          # 本地文件的完整路径,例如D:\localPath\exampleFile.png
          file_path = 'D:\localPath\exampleFile.png'
      
          # 获取文件上传token
          upload_token = token_dict.setdefault(endpoint, None)
          if (upload_token == None) or int(upload_token.expiration) <= int(time.time()):
              response = client.describe_upload_token()
              upload_token = response.body.data
              token_dict[endpoint] = upload_token
          # 上传文件
          object_name = upload_file(file_path, upload_token)
      
          # 检测参数构造。
          service_parameters = {
              # 待检测文件所在bucket名称。
              'ossBucketName': upload_token.bucket_name,
              # 待检测文件。
              'ossObjectName': object_name,
              # 数据唯一标识
              'dataId': str(uuid.uuid1())
          }
      
          image_async_moderation_request = models.ImageAsyncModerationRequest(
              # 图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
              # 支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
              service='baselineCheck',
              service_parameters=json.dumps(service_parameters)
          )
      
          try:
              return client.image_async_moderation_with_options(image_async_moderation_request, runtime)
          except Exception as err:
              print(err)
      
      
      if __name__ == '__main__':
          # 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
          # 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
          # 常见获取环境变量方式:
          # 获取RAM用户AccessKey ID:os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
          # 获取RAM用户AccessKey Secret:os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
          access_key_id = '建议从环境变量中获取RAM用户AccessKey ID'
          access_key_secret = '建议从环境变量中获取RAM用户AccessKey Secret'
          # 接入区域和地址请根据实际情况修改。
          response = invoke_function(access_key_id, access_key_secret, 'green-cip.cn-shanghai.aliyuncs.com')
          # 自动路由。
          if response is not None:
              if UtilClient.equal_number(500,
                                         response.status_code) or (response.body is not None and 200 != response.body.code):
                  # 区域切换到cn-beijing。
                  response = invoke_function(access_key_id, access_key_secret, 'green-cip.cn-beijing.aliyuncs.com')
      
              if response.status_code == 200:
                  # 调用成功。
                  # 获取审核结果。
                  result = response.body
                  print('response success. result:{}'.format(result))
                  if result.code == 200:
                      result_data = result.data
                      print('reqId: {}'.format(result_data.req_id))
              else:
                  print('response not success. status:{} ,result:{}'.format(response.status_code, response))
      

      获取异步图片检测结果

      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      
      config = Config(
          access_key_id='推荐从环境变量获取AccessKey Id',
          access_key_secret='推荐从环境变量获取AccessKey Secret',
          # 连接时超时时间,单位毫秒(ms)。
          connect_timeout=3000,
          # 读取时超时时间,单位毫秒(ms)。
          read_timeout=6000,
          region_id='cn-shanghai',
          endpoint='green-cip.cn-shanghai.aliyuncs.com'
      )
      clt = Client(config)
      
      DescribeImageModerationResultRequest = models.DescribeImageModerationResultRequest(
          req_id='64C35F30-FFB3-5312-96E1-04DC8D2AE19D'
      )
      try:
          response = clt.describe_image_moderation_result(DescribeImageModerationResultRequest)
          if response.status_code == 200:
              body = response.body
              print('requestId:{}'.format(body.request_id))
              print('code:{}'.format(body.code))
              print('msg:{}'.format(body.msg))
              if body.code == 200:
                  data = body.data
                  print(data.to_map())
                  print('dataId:{}'.format(data.data_id))
                  print('riskLevel:{}'.format(data.risk_level))
                  result = data.result[0]
                  print(result.to_map())
              else:
                  print('response not success. code:{},msg:{}'.format(body.code, body.msg))
          else:
              print('response not success. status:{},result:{}'.format(response.status_code, response))
      
      except Exception as err:
          print(err)
      
    • service同步接口接入示例

      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      from alibabacloud_tea_util.client import Client as UtilClient
      from alibabacloud_tea_util import models as util_models
      import json
      import uuid
      import oss2
      import time
      
      # 服务是否部署在vpc上
      is_vpc = False
      # 文件上传token endpoint->token
      token_dict = dict()
      # 上传文件客户端
      bucket = None
      
      
      # 创建请求客户端
      def create_client(access_key_id, access_key_secret, endpoint):
          config = Config(
              access_key_id=access_key_id,
              access_key_secret=access_key_secret,
              # 设置http代理。
              # http_proxy='http://10.10.xx.xx:xxxx',
              # 设置https代理。
              # https_proxy='https://10.10.xx.xx:xxxx',
              # 接入区域和地址请根据实际情况修改。
              endpoint=endpoint
          )
          return Client(config)
      
      
      # 创建文件上传客户端
      def create_oss_bucket(is_vpc, upload_token):
          global token_dict
          global bucket
          auth = oss2.StsAuth(upload_token.access_key_id, upload_token.access_key_secret, upload_token.security_token)
      
          if (is_vpc):
              end_point = upload_token.oss_internal_end_point
          else:
              end_point = upload_token.oss_internet_end_point
          # 注意:此处实例化的bucket请尽可能重复使用,避免重复建立连接,提升检测性能。
          bucket = oss2.Bucket(auth, end_point, upload_token.bucket_name)
      
      
      # 上传文件
      def upload_file(file_name, upload_token):
          create_oss_bucket(is_vpc, upload_token)
          object_name = upload_token.file_name_prefix + str(uuid.uuid1()) + '.' + file_name.split('.')[-1]
          bucket.put_object_from_file(object_name, file_name)
          return object_name
      
      
      def invoke_function(access_key_id, access_key_secret, endpoint):
          # 注意:此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
          client = create_client(access_key_id, access_key_secret, endpoint)
          # 创建RuntimeObject实例并设置运行参数。
          runtime = util_models.RuntimeOptions()
      
          # 本地文件的完整路径,例如D:\localPath\exampleFile.png
          file_path = 'D:\localPath\exampleFile.png'
      
          # 获取文件上传token
          upload_token = token_dict.setdefault(endpoint, None)
          if (upload_token == None) or int(upload_token.expiration) <= int(time.time()):
              response = client.describe_upload_token()
              upload_token = response.body.data
              token_dict[endpoint] = upload_token
          # 上传文件
          object_name = upload_file(file_path, upload_token)
      
          # 检测参数构造。
          service_parameters = {
              # 待检测文件所在bucket名称。
              'ossBucketName': upload_token.bucket_name,
              # 待检测文件。
              'ossObjectName': object_name,
              # 数据唯一标识
              'dataId': str(uuid.uuid1())
          }
      
          image_batch_moderation_request = models.ImageBatchModerationRequest(
              # 图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
              service='baselineCheck,aigcCheck',
              service_parameters=json.dumps(service_parameters)
          )
      
          try:
              return client.image_batch_moderation_with_options(image_batch_moderation_request, runtime)
          except Exception as err:
              print(err)
      
      
      if __name__ == '__main__':
          # 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
          # 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
          # 常见获取环境变量方式:
          # 获取RAM用户AccessKey ID:os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
          # 获取RAM用户AccessKey Secret:os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
          access_key_id = '建议从环境变量中获取RAM用户AccessKey ID'
          access_key_secret = '建议从环境变量中获取RAM用户AccessKey Secret'
          # 接入区域和地址请根据实际情况修改。
          response = invoke_function(access_key_id, access_key_secret, 'green-cip.cn-shanghai.aliyuncs.com')
          # 自动路由。
          if response is not None:
              if UtilClient.equal_number(500,
                                         response.status_code) or (response.body is not None and 200 != response.body.code):
                  # 区域切换到cn-beijing。
                  response = invoke_function(access_key_id, access_key_secret, 'green-cip.cn-beijing.aliyuncs.com')
      
              if response.status_code == 200:
                  # 调用成功。
                  # 获取审核结果。
                  result = response.body
                  print('requestId:{}'.format(result.request_id))
                  print('code:{}'.format(result.code))
                  print('msg:{}'.format(result.msg))
                  if result.code == 200:
                      data = result.data
                      print('riskLevel:{}'.format(data.risk_level))
                      print(data.to_map())
              else:
                  print('response not success. status:{} ,result:{}'.format(response.status_code, response))
      

使用OSS图片进行检测

使用场景

如果您需要审核的图片文件已经存储在阿里云对象存储OSS中,你可授权创建服务角色,允许内容安全服务访问对象存储OSS。图片审核增强版服务会通过服务角色获取到对象存储OSS的文件后进行审核。访问云资源访问授权页面创建服务角色。

  1. 使用阿里云账号(即主账号)访问云资源访问授权页面进行授权。

  2. 执行如下命令安装Python SDK。

    pip install alibabacloud_green20220302==2.19.1
  3. 接入Python SDK。

    • 同步接口接入示例

      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      from alibabacloud_tea_util.client import Client as UtilClient
      from alibabacloud_tea_util import models as util_models
      import json
      import os
      import uuid
      
      
      # 创建请求客户端
      def create_client(access_key_id, access_key_secret, endpoint):
          config = Config(
              access_key_id=access_key_id,
              access_key_secret=access_key_secret,
              # 设置http代理。
              # http_proxy='http://10.10.xx.xx:xxxx',
              # 设置https代理。
              # https_proxy='https://10.10.xx.xx:xxxx',
              # 接入区域和地址请根据实际情况修改。
              endpoint=endpoint
          )
          return Client(config)
      
      
      def invoke_function(access_key_id, access_key_secret, endpoint):
          # 注意:此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
          client = create_client(access_key_id, access_key_secret, endpoint)
          # 创建RuntimeObject实例并设置运行参数。
          runtime = util_models.RuntimeOptions()
      
          # 检测参数构造。
          service_parameters = {
              # 待检测文件所在bucket的区域。 示例:cn-shanghai
              'ossRegionId': 'cn-shanghai',
              # 待检测文件所在bucket名称。示例:bucket001
              'ossBucketName': 'bucket001',
              # 待检测文件。 示例:image/001.jpg
              'ossObjectName': 'image/001.jpg',
              # 数据唯一标识
              'dataId': str(uuid.uuid1())
          }
      
          image_moderation_request = models.ImageModerationRequest(
              # 图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
              # 支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
            	service='baselineCheck',
              service_parameters=json.dumps(service_parameters)
          )
      
          try:
              return client.image_moderation_with_options(image_moderation_request, runtime)
          except Exception as err:
              print(err)
      
      
      if __name__ == '__main__':
          # 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
          # 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
          # 常见获取环境变量方式:
          # 获取RAM用户AccessKey ID:os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
          # 获取RAM用户AccessKey Secret:os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
          access_key_id='建议从环境变量中获取RAM用户AccessKey ID'
          access_key_secret='建议从环境变量中获取RAM用户AccessKey Secret'
          # 接入区域和地址请根据实际情况修改。
          response = invoke_function(access_key_id, access_key_secret, 'green-cip.cn-shanghai.aliyuncs.com')
          # 自动路由。
          if response is not None:
              if UtilClient.equal_number(500,
                                         response.status_code) or (response.body is not None and 200 != response.body.code):
                  # 区域切换到cn-beijing。
                  response = invoke_function(access_key_id, access_key_secret, 'green-cip.cn-beijing.aliyuncs.com')
      
              if response.status_code == 200:
                  # 调用成功。
                  # 获取审核结果。
                  result = response.body
                  print('response success. result:{}'.format(result))
                  if result.code == 200:
                      result_data = result.data
                      print('result: {}'.format(result_data))
              else:
                  print('response not success. status:{} ,result:{}'.format(response.status_code, response))
      
    • 异步接口接入示例

      提交异步图片检测任务

      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      import json
      import uuid
      
      config = Config(
          access_key_id='推荐从环境变量获取AccessKey Id',
          access_key_secret='推荐从环境变量获取AccessKey Secret',
          # 连接时超时时间,单位毫秒(ms)。
          connect_timeout=3000,
          # 读取时超时时间,单位毫秒(ms)。
          read_timeout=6000,
          region_id='cn-shanghai',
          endpoint='green-cip.cn-shanghai.aliyuncs.com'
      )
      clt = Client(config)
      serviceParameters = {
          'ossBucketName': 'bucket_01',
          'ossObjectName': '2022023/04/24/test.jpg',
          'ossRegionId': 'cn-shanghai',
          'dataId': str(uuid.uuid4()),
          'infoType': 'logoData'
      }
      ImageAsyncModerationRequest = models.ImageAsyncModerationRequest(
          # 检测类型: baselineCheck 通⽤基线检测
          service='baselineCheck',
          service_parameters=json.dumps(serviceParameters)
      )
      try:
          response = clt.image_async_moderation(ImageAsyncModerationRequest)
          if response.status_code == 200:
              body = response.body
              print('requestId:{}'.format(body.request_id))
              print('code:{}'.format(body.code))
              print('msg:{}'.format(body.msg))
              if body.code == 200:
                  data = body.data
                  print('reqId:{}'.format(data.req_id))
              else:
                  print('response not success. code:{},msg:{}'.format(body.code, body.msg))
          else:
              print('response not success. status:{},result:{}'.format(response.status_code, response))
      
      except Exception as err:
          print(err)
      

      获取异步图片检测结果

      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      
      config = Config(
          access_key_id='推荐从环境变量获取AccessKey Id',
          access_key_secret='推荐从环境变量获取AccessKey Secret',
          # 连接时超时时间,单位毫秒(ms)。
          connect_timeout=3000,
          # 读取时超时时间,单位毫秒(ms)。
          read_timeout=6000,
          region_id='cn-shanghai',
          endpoint='green-cip.cn-shanghai.aliyuncs.com'
      )
      clt = Client(config)
      
      DescribeImageModerationResultRequest = models.DescribeImageModerationResultRequest(
          req_id='64C35F30-FFB3-5312-96E1-04DC8D2AE19D'
      )
      try:
          response = clt.describe_image_moderation_result(DescribeImageModerationResultRequest)
          if response.status_code == 200:
              body = response.body
              print('requestId:{}'.format(body.request_id))
              print('code:{}'.format(body.code))
              print('msg:{}'.format(body.msg))
              if body.code == 200:
                  data = body.data
                  print(data.to_map())
                  print('dataId:{}'.format(data.data_id))
                  print('riskLevel:{}'.format(data.risk_level))
                  result = data.result[0]
                  print(result.to_map())
              else:
                  print('response not success. code:{},msg:{}'.format(body.code, body.msg))
          else:
              print('response not success. status:{},result:{}'.format(response.status_code, response))
      
      except Exception as err:
          print(err)
      
    • service同步接口接入示例

      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      from alibabacloud_tea_util import models as util_models
      import json
      import uuid
      
      
      def create_client(access_key_id, access_key_secret, endpoint):
          config = Config(
              access_key_id=access_key_id,
              access_key_secret=access_key_secret,
              endpoint=endpoint
          )
          return Client(config)
      
      
      def invoke_function(access_key_id, access_key_secret, endpoint):
          client = create_client(access_key_id, access_key_secret, endpoint)
          runtime = util_models.RuntimeOptions()
          service_parameters = {
              # 待检测文件所在bucket的区域。 示例:cn-shanghai
              'ossRegionId': 'cn-shanghai',
              # 待检测文件所在bucket名称。示例:bucket001
              'ossBucketName': 'bucket001',
              # 待检测文件。 示例:image/001.jpg
              'ossObjectName': 'image/001.jpg',
              'dataId': str(uuid.uuid1())
          }
          image_batchtion_request = models.ImageBatchModerationRequest(
              'baselineCheck,baselineCheck_pro',
              json.dumps(service_parameters)
      
          )
      
          try:
              return client.image_batch_moderation_with_options(image_batchtion_request, runtime)
          except Exception as err:
              print(err)
      
      
      if __name__ == '__main__':
          access_key_id = '建议从环境变量中获取RAM用户AccessKey ID'
          access_key_secret = '建议从环境变量中获取RAM用户AccessKey Secret'
          response = invoke_function(access_key_id, access_key_secret, 'green-cip.cn-shanghai.aliyuncs.com')
          print('response:{}', response)
      
          if response is not None:
              if response.status_code == 200:
                  result = response.body
                  print('response success. result:{}'.format(result))
                  if result.code == 200:
                      result_data = result.data
                      print('result: {}'.format(result_data))
              else:
                  print('response not success. status:{} ,result:{}'.format(response.status_code, response))
      

PHP SDK

支持PHP 5.6及以上版本。

原始代码,请参见PHP SDK源码

支持以下三种类型的图片检测。

对公网可访问图片进行检测

使用场景

当需要审核的图片可通过公网链接访问时,图片审核增强版服务可通过图片URL获取文件后进行审核。

  1. 安装PHP SDK。

    执行如下命令引入相关依赖。

    composer require alibabacloud/green-20220302 2.19.1
  2. 接入PHP SDK。

    • 同步接口接入示例

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationResponse;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationRequest;
      use AlibabaCloud\Tea\Utils\Utils;
      
      /**
       * 创建请求客户端
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return Green
       */
      function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
      {
          $config = new Config([
              "accessKeyId" => $accessKeyId,
              "accessKeySecret" => $accessKeySecret,
              // 设置HTTP代理。
              // "httpProxy" => "http://10.10.xx.xx:xxxx",
              // 设置HTTPS代理。
              // "httpsProxy" => "https://10.10.xx.xx:xxxx",
              "endpoint" => $endpoint,
          ]);
          return new Green($config);
      }
      
      /**
       * 提交检测任务
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return ImageModerationResponse
       */
      function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageModerationResponse
      {
          // 注意:此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
          $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
          // 创建RuntimeObject实例并设置运行参数。
          $runtime = new RuntimeOptions([]);
          
          // 检测参数构造。
        	$request = new ImageModerationRequest();
          $serviceParameters = array(
              // 待检测图片,公网可访问的URL。
              'imageUrl' => 'https://img.alicdn.com/tfs/xxxxxxxxxx001.png',
              // 检测数据唯一标识。
              'dataId' => uniqid());
        	// 图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
        	// 支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff  
        	$request->service = "baselineCheck";
          $request->serviceParameters = json_encode($serviceParameters);
          // 提交检测
          return $client->imageModerationWithOptions($request, $runtime);
      }
      
      /**
      * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
      * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
      * 常见获取环境变量方式:
      * 获取RAM用户AccessKey ID:getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
      * 获取RAM用户AccessKey Secret:getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
      */
      $accessKeyId = '建议从环境变量中获取RAM用户AccessKey ID';
      $accessKeySecret = '建议从环境变量中获取RAM用户AccessKey Secret';
      // 接入区域和地址请根据实际情况修改
      $endpoint = "green-cip.cn-shanghai.aliyuncs.com";
      
      try {
          $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          // 自动路由。
          if (Utils::equalNumber(500, $response->statusCode) || Utils::equalNumber(500, $response->body->code)) {
              //区域切换到cn-beijing。
              $endpoint = "green-cip.cn-beijing.aliyuncs.com";
              $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          }
          print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE));
      } catch (Exception $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }
      
    • 异步接口接入示例

      提交异步图片检测任务

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageAsyncModerationResponse;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageAsyncModerationRequest;
      use AlibabaCloud\Tea\Utils\Utils;
      
      /**
       * 创建请求客户端
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return Green
       */
      function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
      {
          $config = new Config([
              "accessKeyId" => $accessKeyId,
              "accessKeySecret" => $accessKeySecret,
              // 设置HTTP代理。
              // "httpProxy" => "http://10.10.xx.xx:xxxx",
              // 设置HTTPS代理。
              // "httpsProxy" => "https://10.10.xx.xx:xxxx",
              "endpoint" => $endpoint,
          ]);
          return new Green($config);
      }
      
      /**
       * 提交检测任务
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return ImageAsyncModerationResponse
       */
      function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageAsyncModerationResponse
      {
          // 注意:此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
          $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
          // 创建RuntimeObject实例并设置运行参数。
          $runtime = new RuntimeOptions([]);
          
          // 检测参数构造。
          $request = new ImageAsyncModerationRequest();
          $serviceParameters = array(
              // 待检测图片,公网可访问的URL。
              'imageUrl' => 'https://www.aliyun.com/img/000645/a6c2fa1b2c6de60e6c3a570995fd76e0.jpg',
              );
          // 图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
          $request->service = "baselineCheck";
          $request->serviceParameters = json_encode($serviceParameters);
          // 提交检测
          return $client->imageAsyncModerationWithOptions($request, $runtime);
      }
      
      /**
      * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
      * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
      * 常见获取环境变量方式:
      * 获取RAM用户AccessKey ID:getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
      * 获取RAM用户AccessKey Secret:getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
      */
      $accessKeyId = '建议从环境变量中获取RAM用户AccessKey ID';
      $accessKeySecret = '建议从环境变量中获取RAM用户AccessKey Secret';
      // 接入区域和地址请根据实际情况修改
      $endpoint = "green-cip.cn-shanghai.aliyuncs.com";
      
      try {
          $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          // 自动路由。
          if (Utils::equalNumber(500, $response->statusCode) || Utils::equalNumber(500, $response->body->code)) {
              //区域切换到cn-beijing。
              $endpoint = "green-cip.cn-beijing.aliyuncs.com";
              $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          }
          print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE));
      } catch (Exception $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }

      获取异步图片检测结果

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\DescribeImageModerationResultResponse;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      use AlibabaCloud\SDK\Green\V20220302\Models\DescribeImageModerationResultRequest;
      use AlibabaCloud\Tea\Utils\Utils;
      
      /**
       * 创建请求客户端
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return Green
       */
      function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
      {
          $config = new Config([
              "accessKeyId" => $accessKeyId,
              "accessKeySecret" => $accessKeySecret,
              // 设置HTTP代理。
              // "httpProxy" => "http://10.10.xx.xx:xxxx",
              // 设置HTTPS代理。
              // "httpsProxy" => "https://10.10.xx.xx:xxxx",
              "endpoint" => $endpoint,
          ]);
          return new Green($config);
      }
      
      /**
       * 提交检测任务
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return DescribeImageModerationResultResponse
       */
      function invoke($accessKeyId, $accessKeySecret, $endpoint): DescribeImageModerationResultResponse
      {
          // 注意:此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
          $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
          // 创建RuntimeObject实例并设置运行参数。
          $runtime = new RuntimeOptions([]);
          
          // 检测参数构造。
          $request = new DescribeImageModerationResultRequest();
      
          $request->reqId = "2515AE5C-8EB3-5925-84C4-30F2195EAAD1";
          // 提交检测
          return $client->describeImageModerationResultWithOptions($request, $runtime);
      }
      
      /**
      * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
      * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
      * 常见获取环境变量方式:
      * 获取RAM用户AccessKey ID:getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
      * 获取RAM用户AccessKey Secret:getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
      */
      $accessKeyId = '建议从环境变量中获取RAM用户AccessKey ID';
      $accessKeySecret = '建议从环境变量中获取RAM用户AccessKey Secret';
      // 接入区域和地址请根据实际情况修改
      $endpoint = "green-cip.cn-shanghai.aliyuncs.com";
      
      try {
          $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE));
      } catch (Exception $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }
    • service同步接口接入示例

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageBatchModerationResponse;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageBatchModerationRequest;
      use AlibabaCloud\Tea\Utils\Utils;
      
      /**
       * 创建请求客户端
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return Green
       */
      function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
      {
          $config = new Config([
              "accessKeyId" => $accessKeyId,
              "accessKeySecret" => $accessKeySecret,
              // 设置HTTP代理。
              // "httpProxy" => "http://10.10.xx.xx:xxxx",
              // 设置HTTPS代理。
              // "httpsProxy" => "https://10.10.xx.xx:xxxx",
              "endpoint" => $endpoint,
          ]);
          return new Green($config);
      }
      
      /**
       * 提交检测任务
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return ImageBatchModerationResponse
       */
      function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageBatchModerationResponse
      {
          // 注意:此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
          $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
          // 创建RuntimeObject实例并设置运行参数。
          $runtime = new RuntimeOptions([]);
          
          // 检测参数构造。
        	$request = new ImageBatchModerationRequest();
          $serviceParameters = array(
              // 待检测图片,公网可访问的URL。
              'imageUrl' => 'https://www.aliyun.com/img/2fa1b2c6de60e6c3a570995fd76e0.jpg',
              'dataId' => uniqid());
        	// 图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
        	// 支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff  
        	$request->service = "baselineCheck,profilePhotoCheck";
          $request->serviceParameters = json_encode($serviceParameters);
          // 提交检测
          return $client->imageBatchModerationWithOptions($request, $runtime);
      }
      
      /**
      * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
      * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
      * 常见获取环境变量方式:
      * 获取RAM用户AccessKey ID:getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
      * 获取RAM用户AccessKey Secret:getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
      */
      $accessKeyId = '建议从环境变量中获取RAM用户AccessKey ID';
      $accessKeySecret = '建议从环境变量中获取RAM用户AccessKey Secret';
      // 接入区域和地址请根据实际情况修改
      $endpoint = "green-cip.cn-shanghai.aliyuncs.com";
      
      try {
          $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          // 自动路由。
          if (Utils::equalNumber(500, $response->statusCode) || Utils::equalNumber(500, $response->body->code)) {
              //区域切换到cn-beijing。
              $endpoint = "green-cip.cn-beijing.aliyuncs.com";
              $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          }
          print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE));
      } catch (Exception $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }

对本地图片进行检测

使用场景

当您需要审核的图片在本地机器且无公网访问链接,您可以将图片上传到内容安全提供的对象存储OSS Bucket中,图片审核增强版服务可直接访问对象存储OSS,获取到图片内容后进行审核。

  1. 安装PHP SDK。

    安装内容安全SDK:

    composer require alibabacloud/green-20220302 2.19.1

    安装OSS SDK:

    composer require aliyuncs/oss-sdk-php
  2. 接入PHP SDK。

    • 同步接口接入示例

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationResponse;
      use AlibabaCloud\Tea\Utils\Utils;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationRequest;
      use OSS\OssClient;
      
      // 服务是否部署在VPC上
      $isVPC = false;
      // 文件上传token
      $tokenArray = array();
      // 文件上传请求客户端
      $ossClient = null;
      
      /**
       * 创建请求客户端
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return Green
       */
      function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
      {
          $config = new Config([
              "accessKeyId" => $accessKeyId,
              "accessKeySecret" => $accessKeySecret,
              // 设置HTTP代理。
              // "httpProxy" => "http://10.10.xx.xx:xxxx",
              // 设置HTTPS代理。
              // "httpsProxy" => "https://10.10.xx.xx:xxxx",
              "endpoint" => $endpoint,
          ]);
          return new Green($config);
      }
      
      /**
       * 创建文件上传客户端
       * @param $tokenData
       * @return void
       */
      function create_upload_client($tokenData): void
      {
      
          global $isVPC;
          global $ossClient;
          // 注意:此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
          if ($isVPC) {
              $ossClient = new OssClient($tokenData->accessKeyId, $tokenData->accessKeySecret, $tokenData->ossInternalEndPoint, false, $tokenData->securityToken);
          } else {
              $ossClient = new OssClient($tokenData->accessKeyId, $tokenData->accessKeySecret, $tokenData->ossInternetEndPoint, false, $tokenData->securityToken);
          }
      }
      
      /**
       * 上传文件
       * @param $fileName
       * @param $tokenData
       * @return string
       * @throws \OSS\Core\OssException
       */
      function upload_file($filePath, $tokenData): string
      {
          global $ossClient;
          //初始化OssClient
          create_upload_client($tokenData);
          $split = explode(".", $filePath);
          if (count($split) > 1) {
              $objectName = $tokenData->fileNamePrefix . uniqid() . "." . explode(".", $filePath)[count($split) - 1];
          } else {
              $objectName = $tokenData->fileNamePrefix . uniqid();
          }
          //上传文件
          $ossClient->uploadFile($tokenData->bucketName, $objectName, $filePath);
          return $objectName;
      }
      
      /**
       * 提交检测任务
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return ImageModerationResponse
       * @throws \OSS\Core\OssException
       */
      function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageModerationResponse
      {
          global $tokenArray;
          // 注意:此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
          $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
          // 创建RuntimeObject实例并设置运行参数。
          $runtime = new RuntimeOptions([]);
          // 本地文件的完整路径,例如D:\\localPath\\exampleFile.png。
          $filePath = "D:\\localPath\\exampleFile.png";
      
          //获取文件上传token
          if (!isset($tokenArray[$endpoint]) || $tokenArray[$endpoint]->expiration <= time()) {
              $token = $client->describeUploadToken();
              $tokenArray[$endpoint] = $token->body->data;
          }
      
          // 上传文件
          $objectName = upload_file($filePath, $tokenArray[$endpoint]);
      
          // 检测参数构造。
          $request = new ImageModerationRequest();
          // 图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
          // 支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
        	$request->service = "baselineCheck";
          // 待检测图片Oss信息。
          $serviceParameters = array(
              'ossObjectName' => $objectName,
              'ossBucketName' => $tokenArray[$endpoint]->bucketName,
              'dataId' => uniqid());
          $request->serviceParameters = json_encode($serviceParameters);
          // 提交检测
          return $client->imageModerationWithOptions($request, $runtime);
      }
      
      /**
      * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
      * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
      * 常见获取环境变量方式:
      * 获取RAM用户AccessKey ID:getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
      * 获取RAM用户AccessKey Secret:getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
      */
      $accessKeyId = '建议从环境变量中获取RAM用户AccessKey ID';
      $accessKeySecret = '建议从环境变量中获取RAM用户AccessKey Secret';
      // 接入区域和地址请根据实际情况修改
      $endpoint = "green-cip.cn-shanghai.aliyuncs.com";
      
      try {
          $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          // 自动路由。
          if (Utils::equalNumber(500, $response->statusCode) || Utils::equalNumber(500, $response->body->code)) {
              //区域切换到cn-beijing。
              $endpoint = "green-cip.cn-beijing.aliyuncs.com";
              $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          }
          print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE));
      } catch (Exception $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }
    • 异步接口接入示例

      提交异步图片检测任务

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageAsyncModerationResponse;
      use AlibabaCloud\Tea\Utils\Utils;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageAsyncModerationRequest;
      use OSS\OssClient;
      
      // 服务是否部署在VPC上
      $isVPC = false;
      // 文件上传token
      $tokenArray = array();
      // 文件上传请求客户端
      $ossClient = null;
      
      /**
       * 创建请求客户端
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return Green
       */
      function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
      {
          $config = new Config([
              "accessKeyId" => $accessKeyId,
              "accessKeySecret" => $accessKeySecret,
              // 设置HTTP代理。
              // "httpProxy" => "http://10.10.xx.xx:xxxx",
              // 设置HTTPS代理。
              // "httpsProxy" => "https://10.10.xx.xx:xxxx",
              "endpoint" => $endpoint,
          ]);
          return new Green($config);
      }
      
      /**
       * 创建文件上传客户端
       * @param $tokenData
       * @return void
       */
      function create_upload_client($tokenData): void
      {
      
          global $isVPC;
          global $ossClient;
          // 注意:此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
          if ($isVPC) {
              $ossClient = new OssClient($tokenData->accessKeyId, $tokenData->accessKeySecret, $tokenData->ossInternalEndPoint, false, $tokenData->securityToken);
          } else {
              $ossClient = new OssClient($tokenData->accessKeyId, $tokenData->accessKeySecret, $tokenData->ossInternetEndPoint, false, $tokenData->securityToken);
          }
      }
      
      /**
       * 上传文件
       * @param $fileName
       * @param $tokenData
       * @return string
       * @throws \OSS\Core\OssException
       */
      function upload_file($filePath, $tokenData): string
      {
          global $ossClient;
          //初始化OssClient
          create_upload_client($tokenData);
          $split = explode(".", $filePath);
          if (count($split) > 1) {
              $objectName = $tokenData->fileNamePrefix . uniqid() . "." . explode(".", $filePath)[count($split) - 1];
          } else {
              $objectName = $tokenData->fileNamePrefix . uniqid();
          }
          //上传文件
          $ossClient->uploadFile($tokenData->bucketName, $objectName, $filePath);
          return $objectName;
      }
      
      /**
       * 提交检测任务
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return ImageAsyncModerationResponse
       * @throws \OSS\Core\OssException
       */
      function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageAsyncModerationResponse
      {
          global $tokenArray;
          // 注意:此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
          $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
          // 创建RuntimeObject实例并设置运行参数。
          $runtime = new RuntimeOptions([]);
          // 本地文件的完整路径,例如D:\\localPath\\exampleFile.png。
          $filePath = "D:\\localPath\\exampleFile.png";
      
          //获取文件上传token
          if (!isset($tokenArray[$endpoint]) || $tokenArray[$endpoint]->expiration <= time()) {
              $token = $client->describeUploadToken();
              $tokenArray[$endpoint] = $token->body->data;
          }
      
          // 上传文件
          $objectName = upload_file($filePath, $tokenArray[$endpoint]);
      
          // 检测参数构造。
          $request = new ImageAsyncModerationRequest();
          // 图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
          // 支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
            $request->service = "baselineCheck";
          // 待检测图片Oss信息。
          $serviceParameters = array(
              'ossObjectName' => $objectName,
              'ossBucketName' => $tokenArray[$endpoint]->bucketName,
              'dataId' => uniqid());
          $request->serviceParameters = json_encode($serviceParameters);
          // 提交检测
          return $client->imageAsyncModerationWithOptions($request, $runtime);
      }
      
      /**
      * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
      * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
      * 常见获取环境变量方式:
      * 获取RAM用户AccessKey ID:getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
      * 获取RAM用户AccessKey Secret:getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
      */
      $accessKeyId = '建议从环境变量中获取RAM用户AccessKey ID';
      $accessKeySecret = '建议从环境变量中获取RAM用户AccessKey Secret';
      // 接入区域和地址请根据实际情况修改
      $endpoint = "green-cip.cn-shanghai.aliyuncs.com";
      
      try {
          $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          // 自动路由。
          if (Utils::equalNumber(500, $response->statusCode) || Utils::equalNumber(500, $response->body->code)) {
              //区域切换到cn-beijing。
              $endpoint = "green-cip.cn-beijing.aliyuncs.com";
              $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          }
          print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE));
      } catch (Exception $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }

      获取异步图片检测结果

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\DescribeImageModerationResultResponse;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      use AlibabaCloud\SDK\Green\V20220302\Models\DescribeImageModerationResultRequest;
      use AlibabaCloud\Tea\Utils\Utils;
      
      /**
       * 创建请求客户端
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return Green
       */
      function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
      {
          $config = new Config([
              "accessKeyId" => $accessKeyId,
              "accessKeySecret" => $accessKeySecret,
              // 设置HTTP代理。
              // "httpProxy" => "http://10.10.xx.xx:xxxx",
              // 设置HTTPS代理。
              // "httpsProxy" => "https://10.10.xx.xx:xxxx",
              "endpoint" => $endpoint,
          ]);
          return new Green($config);
      }
      
      /**
       * 提交检测任务
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return DescribeImageModerationResultResponse
       */
      function invoke($accessKeyId, $accessKeySecret, $endpoint): DescribeImageModerationResultResponse
      {
          // 注意:此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
          $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
          // 创建RuntimeObject实例并设置运行参数。
          $runtime = new RuntimeOptions([]);
          
          // 检测参数构造。
          $request = new DescribeImageModerationResultRequest();
      
          $request->reqId = "2515AE5C-8EB3-5925-84C4-30F2195EAAD1";
          // 提交检测
          return $client->describeImageModerationResultWithOptions($request, $runtime);
      }
      
      /**
      * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
      * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
      * 常见获取环境变量方式:
      * 获取RAM用户AccessKey ID:getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
      * 获取RAM用户AccessKey Secret:getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
      */
      $accessKeyId = '建议从环境变量中获取RAM用户AccessKey ID';
      $accessKeySecret = '建议从环境变量中获取RAM用户AccessKey Secret';
      // 接入区域和地址请根据实际情况修改
      $endpoint = "green-cip.cn-shanghai.aliyuncs.com";
      
      try {
          $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE));
      } catch (Exception $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }
    • service同步接口接入示例

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageBatchModerationResponse;
      use AlibabaCloud\Tea\Utils\Utils;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageBatchModerationRequest;
      use OSS\OssClient;
      
      // 服务是否部署在VPC上
      $isVPC = false;
      // 文件上传token
      $tokenArray = array();
      // 文件上传请求客户端
      $ossClient = null;
      
      /**
       * 创建请求客户端
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return Green
       */
      function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
      {
          $config = new Config([
              "accessKeyId" => $accessKeyId,
              "accessKeySecret" => $accessKeySecret,
              // 设置HTTP代理。
              // "httpProxy" => "http://10.10.xx.xx:xxxx",
              // 设置HTTPS代理。
              // "httpsProxy" => "https://10.10.xx.xx:xxxx",
              "endpoint" => $endpoint,
          ]);
          return new Green($config);
      }
      
      /**
       * 创建文件上传客户端
       * @param $tokenData
       * @return void
       */
      function create_upload_client($tokenData): void
      {
      
          global $isVPC;
          global $ossClient;
          // 注意:此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
          if ($isVPC) {
              $ossClient = new OssClient($tokenData->accessKeyId, $tokenData->accessKeySecret, $tokenData->ossInternalEndPoint, false, $tokenData->securityToken);
          } else {
              $ossClient = new OssClient($tokenData->accessKeyId, $tokenData->accessKeySecret, $tokenData->ossInternetEndPoint, false, $tokenData->securityToken);
          }
      }
      
      /**
       * 上传文件
       * @param $fileName
       * @param $tokenData
       * @return string
       * @throws \OSS\Core\OssException
       */
      function upload_file($filePath, $tokenData): string
      {
          global $ossClient;
          //初始化OssClient
          create_upload_client($tokenData);
          $split = explode(".", $filePath);
          if (count($split) > 1) {
              $objectName = $tokenData->fileNamePrefix . uniqid() . "." . explode(".", $filePath)[count($split) - 1];
          } else {
              $objectName = $tokenData->fileNamePrefix . uniqid();
          }
          //上传文件
          $ossClient->uploadFile($tokenData->bucketName, $objectName, $filePath);
          return $objectName;
      }
      
      /**
       * 提交检测任务
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return ImageBatchModerationResponse
       * @throws \OSS\Core\OssException
       */
      function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageBatchModerationResponse
      {
          global $tokenArray;
          // 注意:此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
          $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
          // 创建RuntimeObject实例并设置运行参数。
          $runtime = new RuntimeOptions([]);
          // 本地文件的完整路径,例如D:\\localPath\\exampleFile.png。
          $filePath = "D:\\localPath\\exampleFile.png";
      
          //获取文件上传token
          if (!isset($tokenArray[$endpoint]) || $tokenArray[$endpoint]->expiration <= time()) {
              $token = $client->describeUploadToken();
              $tokenArray[$endpoint] = $token->body->data;
          }
      
          // 上传文件
          $objectName = upload_file($filePath, $tokenArray[$endpoint]);
      
          // 检测参数构造。
          $request = new ImageBatchModerationRequest();
          // 图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
          // 支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
            $request->service = "baselineCheck,profilePhotoCheck";
          // 待检测图片Oss信息。
          $serviceParameters = array(
              'ossObjectName' => $objectName,
              'ossBucketName' => $tokenArray[$endpoint]->bucketName,
              'dataId' => uniqid());
          $request->serviceParameters = json_encode($serviceParameters);
          // 提交检测
          return $client->imageBatchModerationWithOptions($request, $runtime);
      }
      
      /**
      * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
      * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
      * 常见获取环境变量方式:
      * 获取RAM用户AccessKey ID:getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
      * 获取RAM用户AccessKey Secret:getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
      */
      $accessKeyId = '建议从环境变量中获取RAM用户AccessKey ID';
      $accessKeySecret = '建议从环境变量中获取RAM用户AccessKey Secret';
      // 接入区域和地址请根据实际情况修改
      $endpoint = "green-cip.cn-shanghai.aliyuncs.com";
      
      try {
          $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          // 自动路由。
          if (Utils::equalNumber(500, $response->statusCode) || Utils::equalNumber(500, $response->body->code)) {
              //区域切换到cn-beijing。
              $endpoint = "green-cip.cn-beijing.aliyuncs.com";
              $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          }
          print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE));
      } catch (Exception $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }

OSS图片进行检测

使用场景

如果您需要审核的图片文件已经存储在阿里云对象存储OSS中,你可授权创建服务角色,允许内容安全服务访问对象存储OSS。图片审核增强版服务会通过服务角色获取到对象存储OSS的文件后进行审核。访问云资源访问授权页面创建服务角色。

  1. 使用阿里云账号(即主账号)访问云资源访问授权页面进行授权。

  2. 安装PHP SDK。

    composer require alibabacloud/green-20220302 2.19.1
  3. 接入PHP SDK。

    • 同步接口接入示例

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationResponse;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationRequest;
      use AlibabaCloud\Tea\Utils\Utils;
      
      /**
       * 创建请求客户端
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return Green
       */
      function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
      {
          $config = new Config([
              "accessKeyId" => $accessKeyId,
              "accessKeySecret" => $accessKeySecret,
              // 设置HTTP代理。
              // "httpProxy" => "http://10.10.xx.xx:xxxx",
              // 设置HTTPS代理。
              // "httpsProxy" => "https://10.10.xx.xx:xxxx",
              "endpoint" => $endpoint,
          ]);
          return new Green($config);
      }
      
      /**
       * 提交检测任务
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return ImageModerationResponse
       */
      function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageModerationResponse
      {
          // 注意:此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
          $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
          // 创建RuntimeObject实例并设置运行参数。
          $runtime = new RuntimeOptions([]);
          // 检测参数构造。
          $request = new ImageModerationRequest();
          $serviceParameters = array(
            	// 待检测文件。 示例:image/001.jpg
              'ossObjectName' => 'image/001.jpg',
              // 待检测文件所在bucket的区域。 示例:cn-shanghai
              'ossRegionId' => 'cn-shanghai',
            	// 待检测文件所在bucket名称。示例:bucket001
              'ossBucketName' => 'bucket001',
              // 数据唯一标识。
              'dataId' => uniqid());
          // 图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
          // 支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
        	$request->service = "baselineCheck";
          $request->serviceParameters = json_encode($serviceParameters);
          // 提交检测
          return $client->imageModerationWithOptions($request, $runtime);
      }
      
      /**
      * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
      * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
      * 常见获取环境变量方式:
      * 获取RAM用户AccessKey ID:getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
      * 获取RAM用户AccessKey Secret:getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
      */
      $accessKeyId = '建议从环境变量中获取RAM用户AccessKey ID';
      $accessKeySecret = '建议从环境变量中获取RAM用户AccessKey Secret';
      // 接入区域和地址请根据实际情况修改
      $endpoint = "green-cip.cn-shanghai.aliyuncs.com";
      
      try {
          $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          // 自动路由。
          if (Utils::equalNumber(500, $response->statusCode) || Utils::equalNumber(500, $response->body->code)) {
              //区域切换到cn-beijing。
              $endpoint = "green-cip.cn-beijing.aliyuncs.com";
              $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          }
          print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE));
      } catch (Exception $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }
    • 异步接口接入示例

      提交异步图片检测任务

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageAsyncModerationResponse;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageAsyncModerationRequest;
      use AlibabaCloud\Tea\Utils\Utils;
      
      /**
       * 创建请求客户端
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return Green
       */
      function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
      {
          $config = new Config([
              "accessKeyId" => $accessKeyId,
              "accessKeySecret" => $accessKeySecret,
              // 设置HTTP代理。
              // "httpProxy" => "http://10.10.xx.xx:xxxx",
              // 设置HTTPS代理。
              // "httpsProxy" => "https://10.10.xx.xx:xxxx",
              "endpoint" => $endpoint,
          ]);
          return new Green($config);
      }
      
      /**
       * 提交检测任务
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return ImageAsyncModerationResponse
       */
      function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageAsyncModerationResponse
      {
          // 注意:此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
          $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
          // 创建RuntimeObject实例并设置运行参数。
          $runtime = new RuntimeOptions([]);
          
          // 检测参数构造。
          $request = new ImageAsyncModerationRequest();
          $serviceParameters = array(
            	// 待检测文件。 示例:image/001.jpg
              'ossObjectName' => 'image/001.jpg',
              // 待检测文件所在bucket的区域。 示例:cn-shanghai
              'ossRegionId' => 'cn-shanghai',
            	// 待检测文件所在bucket名称。示例:bucket001
              'ossBucketName' => 'bucket001',
              );
          // 图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
          $request->service = "baselineCheck";
          $request->serviceParameters = json_encode($serviceParameters);
          // 提交检测
          return $client->imageAsyncModerationWithOptions($request, $runtime);
      }
      
      /**
      * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
      * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
      * 常见获取环境变量方式:
      * 获取RAM用户AccessKey ID:getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
      * 获取RAM用户AccessKey Secret:getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
      */
      $accessKeyId = '建议从环境变量中获取RAM用户AccessKey ID';
      $accessKeySecret = '建议从环境变量中获取RAM用户AccessKey Secret';
      // 接入区域和地址请根据实际情况修改
      $endpoint = "green-cip.cn-shanghai.aliyuncs.com";
      
      try {
          $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          // 自动路由。
          if (Utils::equalNumber(500, $response->statusCode) || Utils::equalNumber(500, $response->body->code)) {
              //区域切换到cn-beijing。
              $endpoint = "green-cip.cn-beijing.aliyuncs.com";
              $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          }
          print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE));
      } catch (Exception $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }

      获取异步图片检测结果

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\DescribeImageModerationResultResponse;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      use AlibabaCloud\SDK\Green\V20220302\Models\DescribeImageModerationResultRequest;
      use AlibabaCloud\Tea\Utils\Utils;
      
      /**
       * 创建请求客户端
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return Green
       */
      function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
      {
          $config = new Config([
              "accessKeyId" => $accessKeyId,
              "accessKeySecret" => $accessKeySecret,
              // 设置HTTP代理。
              // "httpProxy" => "http://10.10.xx.xx:xxxx",
              // 设置HTTPS代理。
              // "httpsProxy" => "https://10.10.xx.xx:xxxx",
              "endpoint" => $endpoint,
          ]);
          return new Green($config);
      }
      
      /**
       * 提交检测任务
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return DescribeImageModerationResultResponse
       */
      function invoke($accessKeyId, $accessKeySecret, $endpoint): DescribeImageModerationResultResponse
      {
          // 注意:此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
          $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
          // 创建RuntimeObject实例并设置运行参数。
          $runtime = new RuntimeOptions([]);
          
          // 检测参数构造。
          $request = new DescribeImageModerationResultRequest();
      
          $request->reqId = "2515AE5C-8EB3-5925-84C4-30F2195EAAD1";
          // 提交检测
          return $client->describeImageModerationResultWithOptions($request, $runtime);
      }
      
      /**
      * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
      * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
      * 常见获取环境变量方式:
      * 获取RAM用户AccessKey ID:getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
      * 获取RAM用户AccessKey Secret:getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
      */
      $accessKeyId = '建议从环境变量中获取RAM用户AccessKey ID';
      $accessKeySecret = '建议从环境变量中获取RAM用户AccessKey Secret';
      // 接入区域和地址请根据实际情况修改
      $endpoint = "green-cip.cn-shanghai.aliyuncs.com";
      
      try {
          $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE));
      } catch (Exception $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }
    • service同步接口接入示例

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageBatchModerationResponse;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageBatchModerationRequest;
      use AlibabaCloud\Tea\Utils\Utils;
      
      /**
       * 创建请求客户端
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return Green
       */
      function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
      {
          $config = new Config([
              "accessKeyId" => $accessKeyId,
              "accessKeySecret" => $accessKeySecret,
              // 设置HTTP代理。
              // "httpProxy" => "http://10.10.xx.xx:xxxx",
              // 设置HTTPS代理。
              // "httpsProxy" => "https://10.10.xx.xx:xxxx",
              "endpoint" => $endpoint,
          ]);
          return new Green($config);
      }
      
      /**
       * 提交检测任务
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return ImageBatchModerationResponse
       */
      function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageBatchModerationResponse
      {
          // 注意:此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
          $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
          // 创建RuntimeObject实例并设置运行参数。
          $runtime = new RuntimeOptions([]);
          
          // 检测参数构造。
        	$request = new ImageBatchModerationRequest();
          $serviceParameters = array(
                // 待检测文件。 示例:image/001.jpg
              'ossObjectName' => 'image/001.jpg',
              // 待检测文件所在bucket的区域。 示例:cn-shanghai
              'ossRegionId' => 'cn-shanghai',
                // 待检测文件所在bucket名称。示例:bucket001
              'ossBucketName' => 'bucket001',
              'dataId' => uniqid());
        	// 图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
        	// 支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff  
        	$request->service = "baselineCheck,profilePhotoCheck";
          $request->serviceParameters = json_encode($serviceParameters);
          // 提交检测
          return $client->imageBatchModerationWithOptions($request, $runtime);
      }
      
      /**
      * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
      * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
      * 常见获取环境变量方式:
      * 获取RAM用户AccessKey ID:getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
      * 获取RAM用户AccessKey Secret:getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
      */
      $accessKeyId = '建议从环境变量中获取RAM用户AccessKey ID';
      $accessKeySecret = '建议从环境变量中获取RAM用户AccessKey Secret';
      // 接入区域和地址请根据实际情况修改
      $endpoint = "green-cip.cn-shanghai.aliyuncs.com";
      
      try {
          $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          // 自动路由。
          if (Utils::equalNumber(500, $response->statusCode) || Utils::equalNumber(500, $response->body->code)) {
              //区域切换到cn-beijing。
              $endpoint = "green-cip.cn-beijing.aliyuncs.com";
              $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          }
          print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE));
      } catch (Exception $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }

Go SDK

原始代码,请参考Go SDK源码

支持以下三种类型的图片检测。

对公网可访问图片进行检测

使用场景

当需要审核的图片可通过公网链接访问时,图片审核增强版服务可通过图片URL获取文件后进行审核。

  1. 安装Go SDK。

    go get github.com/alibabacloud-go/green-20220302/v2
  2. 接入Go SDK。

    • 同步接口接入示例

      package main
      
      import (
      	"encoding/json"
      	"fmt"
      	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      	green20220302 "github.com/alibabacloud-go/green-20220302/client"
      	util "github.com/alibabacloud-go/tea-utils/v2/service"
      	"github.com/alibabacloud-go/tea/tea"
      	"github.com/google/uuid"
      	"net/http"
      	"os"
      )
      
      //创建请求客户端
      func createClient(accessKeyId *string, accessKeySecret *string, endpoint *string) (*green20220302.Client, error) {
      	config := &openapi.Config{
      		AccessKeyId: accessKeyId,
      		AccessKeySecret: accessKeySecret,
      		// 设置HTTP代理。
      		// HttpProxy: tea.String("http://10.10.xx.xx:xxxx"),
      		// 设置HTTPS代理。
      		// HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
      		Endpoint: endpoint,
      	}
      	//注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
      	return green20220302.NewClient(config);
      }
      
      func invoke(accessKeyId *string, accessKeySecret *string, endpoint *string) (_result *green20220302.ImageModerationResponse, _err error) {
      	//注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
      	client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
      	if _err != nil {
      		return nil,_err
      	}
      	//运行时参数设置,仅对使用了该运行时参数实例的请求有效
      	runtime := &util.RuntimeOptions{}
      
      	//构建图片检测请求。
      	serviceParameters, _ := json.Marshal(
      		map[string]interface{}{
      			//待检测图片链接,公网可访问的URL。
      			"imageUrl": "https://img.alicdn.com/tfs/xxxxxxxxxx001.png",
      			//待检测数据的ID。
      			"dataId":uuid.New(),
      		},
      	)
      	imageModerationRequest := &green20220302.ImageModerationRequest{
      		//图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
      		//支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
          Service:           tea.String("baselineCheck"),
      		ServiceParameters: tea.String(string(serviceParameters)),
      	}
      
      	return client.ImageModerationWithOptions(imageModerationRequest, runtime)
      
      }
      
      func main() {
      	/**
      	 * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
      	 * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
      	 * 常见获取环境变量方式:
      	 * 获取RAM用户AccessKey ID:os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
      	 * 获取RAM用户AccessKey Secret:os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
      	 */
      	var accessKeyId= tea.String("建议从环境变量中获取RAM用户AccessKey ID");
      	var accessKeySecret= tea.String("建议从环境变量中获取RAM用户AccessKey Secret");
      	//接入区域和地址请根据实际情况修改
      	var endpoint = tea.String("green-cip.cn-shanghai.aliyuncs.com");
      	response,_err := invoke(accessKeyId,accessKeySecret,endpoint)
      	//自动路由,区域切换至cn-beijing。
      	flag := false
      	if _err != nil {
      		var err = &tea.SDKError{}
      		if _t, ok := _err.(*tea.SDKError); ok {
      			err = _t
      			// 系统异常,切换到下个地域调用。
      			if *err.StatusCode == 500 {
      				flag = true
      			}
      		}
      	}
      	if response == nil || *response.StatusCode == 500 || *response.Body.Code == 500 {
      		flag = true
      	}
      	if flag {
      		endpoint = tea.String("green-cip.cn-beijing.aliyuncs.com");
      		response, _err = invoke(accessKeyId,accessKeySecret,endpoint)
      	}
      
      	if response != nil {
      		statusCode := tea.IntValue(tea.ToInt(response.StatusCode))
      		body := response.Body
      		imageModerationResponseData := body.Data
      		fmt.Println("requestId:" + tea.StringValue(body.RequestId))
      		if statusCode == http.StatusOK {
      			fmt.Println("response success. response:" + body.String())
      			if tea.IntValue(tea.ToInt(body.Code)) == 200 {
      				result := imageModerationResponseData.Result
      				fmt.Println("response dataId:" + tea.StringValue(imageModerationResponseData.DataId))
      				for i := 0; i < len(result); i++ {
      					fmt.Println("response label:" + tea.StringValue(result[i].Label))
      					fmt.Println("response confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence)))
      				}
      			} else {
      				fmt.Println("image moderation not success. status" + tea.ToString(body.Code))
      			}
      		} else {
      			fmt.Print("response not success. status:" + tea.ToString(statusCode))
      		}
      	}
      }
    • 异步接口接入示例

      提交异步图片检测任务

      package main
      
      import (
      	"encoding/json"
      	"fmt"
      	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      	green "github.com/alibabacloud-go/green-20220302/client"
      	"github.com/alibabacloud-go/tea/tea"
      )
      
      func main() {
      	config := &openapi.Config{
      		AccessKeyId: tea.String("建议从环境变量中获取RAM用户AccessKey ID"),
      		AccessKeySecret: tea.String("建议从环境变量中获取RAM用户AccessKey Secret"),
      		// 访问的 Endpoint
      		Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"),
      		/**
      		 * 请设置超时时间。服务端全链路处理超时时间为10秒,请做相应设置。
      		 * 如果您设置的ReadTimeout小于服务端处理的时间,程序中会获得一个ReadTimeout异常。
      		 */
      		ConnectTimeout: tea.Int(3000),
      		ReadTimeout:    tea.Int(6000),
      	}
      	client, _err := green.NewClient(config)
      	if _err != nil {
      		panic(_err)
      	}
      
      	serviceParameters, _ := json.Marshal(
      		map[string]interface{}{
      			"imageUrl": "https://www.aliyun.com/d206c0754175bede745ce7618f73.jpg",
      		},
      	)
      	request := green.ImageAsyncModerationRequest{
      		Service:           tea.String("baselineCheck"),
      		ServiceParameters: tea.String(string(serviceParameters)),
      	}
      	result, err := client.ImageAsyncModeration(&request)
      	if err != nil {
      		fmt.Print(err.Error())
      	}
      	fmt.Printf("response is %#v\n", result.Body)
      }

      获取异步图片检测结果

      package main
      
      import (
      	"fmt"
      	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      	green "github.com/alibabacloud-go/green-20220302/client"
      	"github.com/alibabacloud-go/tea/tea"
      )
      
      func main() {
      	config := &openapi.Config{
      		AccessKeyId: tea.String("建议从环境变量中获取RAM用户AccessKey ID"),
      		AccessKeySecret: tea.String("建议从环境变量中获取RAM用户AccessKey Secret"),
      		// 访问的 Endpoint
      		Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"),
      		/**
      		 * 请设置超时时间。服务端全链路处理超时时间为10秒,请做相应设置。
      		 * 如果您设置的ReadTimeout小于服务端处理的时间,程序中会获得一个ReadTimeout异常。
      		 */
      		ConnectTimeout: tea.Int(3000),
      		ReadTimeout:    tea.Int(6000),
      	}
      	client, _err := green.NewClient(config)
      	if _err != nil {
      		panic(_err)
      	}
      
      	request := green.DescribeImageModerationResultRequest{
      		ReqId:           tea.String("F30E5B52-12D7-59BB-95F0-5D3AA08ECABF"),
      	}
      	result, err := client.DescribeImageModerationResult(&request)
      	if err != nil {
      		fmt.Print(err.Error())
      	}
      	fmt.Printf("response is %#v\n", result.Body)
      }
    • service同步接口接入示例

      package main
      
      import (
         "encoding/json"
         "fmt"
         openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
         green20220302 "github.com/alibabacloud-go/green-20220302/v2/client"
         util "github.com/alibabacloud-go/tea-utils/v2/service"
         "github.com/alibabacloud-go/tea/tea"
         "github.com/google/uuid"
      )
      
      // 创建请求客户端
      func createClient(accessKeyId *string, accessKeySecret *string, endpoint *string) (*green20220302.Client, error) {
         config := &openapi.Config{
            AccessKeyId: accessKeyId,
            AccessKeySecret: accessKeySecret,
            Endpoint: endpoint,
         }
         return green20220302.NewClient(config)
      }
      
      func invoke(accessKeyId *string, accessKeySecret *string, endpoint *string) (_result *green20220302.ImageBatchModerationResponse, _err error) {
         client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
         if _err != nil {
            return nil, _err
         }
         runtime := &util.RuntimeOptions{}
         serviceParameters, _ := json.Marshal(
            map[string]interface{}{
               //待检测图片链接,公网可访问的URL。
               "imageUrl":"https://img.alicdn.com/tfs/xxxxxxxxxx001.png",
               //待检测数据的ID。
               "dataId": uuid.New(),
            },
         )
      
         ImageBatchModerationRequest := &green20220302.ImageBatchModerationRequest{
            Service:tea.String("baselineCheck,baselineCheck_pro"),
            ServiceParameters: tea.String(string(serviceParameters)),
         }
      
         return client.ImageBatchModerationWithOptions(ImageBatchModerationRequest, runtime)
      
      }
      
      func main() {
         var accessKeyId = tea.String("建议从环境变量中获取RAM用户AccessKey ID")
         var accessKeySecret = tea.String("建议从环境变量中获取RAM用户AccessKey Secret")
         var endpoint = tea.String("green-cip.cn-shanghai.aliyuncs.com")
         response, _err := invoke(accessKeyId, accessKeySecret, endpoint)
         if _err != nil {
            return;
         }
         if response != nil {
            statusCode := tea.IntValue(tea.ToInt(response.StatusCode))
            body := response.Body
            imageBatchModerationResponseData := body.Data
            fmt.Println("requestId:" + tea.StringValue(body.RequestId))
            if statusCode == 200 {
               fmt.Println("response success. response:" + body.String())
               if tea.IntValue(tea.ToInt(body.Code)) == 200 {
                  result := imageBatchModerationResponseData.Result
                  fmt.Println("response dataId:" + tea.StringValue(imageBatchModerationResponseData.DataId))
                  for i := 0; i < len(result); i++ {
                     fmt.Println("response label:" + tea.StringValue(result[i].Label))
                     fmt.Println("response confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence)))
                  }
               } else {
                  fmt.Println("image moderation not success. status" + tea.ToString(body.Code))
               }
            } else {
               fmt.Print("response not success. status:" + tea.ToString(statusCode))
            }
         }
      }
      

对本地图片进行检测

使用场景

当您需要审核的图片在本地机器且无公网访问链接,您可以将图片上传到内容安全提供的对象存储OSS Bucket中,图片审核增强版服务可直接访问对象存储OSS,获取到图片内容后进行审核。

  1. 安装Go SDK。

    安装内容检测SDK:

    go get github.com/alibabacloud-go/green-20220302/v2

    安装OSS SDK:

    go get github.com/aliyun/aliyun-oss-go-sdk/oss
  2. 接入Go SDK。

    • 同步接口接入示例

      package main
      
      import (
      	"encoding/json"
      	"fmt"
      	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      	green20220302 "github.com/alibabacloud-go/green-20220302/client"
      	util "github.com/alibabacloud-go/tea-utils/v2/service"
      	"github.com/alibabacloud-go/tea/tea"
      	"github.com/aliyun/aliyun-oss-go-sdk/oss"
      	"github.com/google/uuid"
      	"net/http"
      	"os"
      	"strings"
      	"time"
      )
      //文件上传token
      var TokenMap =make(map[string]*green20220302.DescribeUploadTokenResponseBodyData)
      //文件上传客户端
      var Bucket *oss.Bucket
      //服务是否部署在VPC上
      var isVPC = false
      //创建请求客户端
      func createClient(accessKeyId string, accessKeySecret string, endpoint string) (*green20220302.Client, error) {
      	config := &openapi.Config{
      		AccessKeyId: tea.String(accessKeyId),
      		AccessKeySecret: tea.String(accessKeySecret),
      		// 设置HTTP代理。
      		// HttpProxy: tea.String("http://10.10.xx.xx:xxxx"),
      		// 设置HTTPS代理。
      		// HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
      		Endpoint: tea.String(endpoint),
      	}
      	//注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
      	return green20220302.NewClient(config);
      }
      
      //创建上传文件客户端
      func createOssClient(tokenData *green20220302.DescribeUploadTokenResponseBodyData) {
      	if isVPC{
      		ossClient, err := oss.New(tea.StringValue(tokenData.OssInternalEndPoint), tea.StringValue(tokenData.AccessKeyId), tea.StringValue(tokenData.AccessKeySecret), oss.SecurityToken(tea.StringValue(tokenData.SecurityToken)))
      		if err != nil {
      			fmt.Println("Error:", err)
      			os.Exit(-1)
      		}
      		Bucket, _ =ossClient.Bucket(tea.StringValue(tokenData.BucketName));
      	}else {
      		ossClient, err := oss.New(tea.StringValue(tokenData.OssInternetEndPoint), tea.StringValue(tokenData.AccessKeyId), tea.StringValue(tokenData.AccessKeySecret), oss.SecurityToken(tea.StringValue(tokenData.SecurityToken)))
      		if err != nil {
      			fmt.Println("Error:", err)
      			os.Exit(-1)
      		}
      		Bucket, _ =ossClient.Bucket(tea.StringValue(tokenData.BucketName));
      	}
      }
      
      //上传文件
      func uploadFile(filePath string,tokenData *green20220302.DescribeUploadTokenResponseBodyData) (string,error) {
      	createOssClient(tokenData)
      	objectName := tea.StringValue(tokenData.FileNamePrefix) + uuid.New().String() + "." + strings.Split(filePath, ".")[1]
      		//上传文件
      		_err := Bucket.PutObjectFromFile(objectName, filePath)
      		if _err != nil {
      			fmt.Println("Error:", _err)
      			os.Exit(-1)
      		}
      	return objectName,_err
      }
      
      func invoke(accessKeyId string, accessKeySecret string, endpoint string) (_result *green20220302.ImageModerationResponse, _err error) {
      	//注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
      	client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
      	if _err != nil {
      		return nil,_err
      	}
      	//运行时参数设置,仅对使用了该运行时参数实例的请求有效
      	runtime := &util.RuntimeOptions{}
      	//本地文件的完整路径,例如D:\localPath\exampleFile.png。
      	var filePath = "D:\\localPath\\exampleFile.png"
      	//获取文件上传临时token
      		tokenData,ok:=TokenMap[endpoint];
      		if !ok || tea.Int32Value(tokenData.Expiration) <= int32(time.Now().Unix()) {
      			//获取文件上传临时token
      			uploadTokenResponse, _err := client.DescribeUploadToken()
      			if _err != nil {
      				return nil,_err
      			}
      			tokenData = uploadTokenResponse.Body.Data
      			TokenMap[endpoint] = tokenData
      		}
      		 var objectName, _ = uploadFile(filePath,TokenMap[endpoint])
      
      	//构建图片检测请求。
      		serviceParameters, _ := json.Marshal(
      			map[string]interface{}{
      				"ossBucketName": tea.StringValue(TokenMap[endpoint].BucketName),
      				"ossObjectName": objectName,
      				"dataId":   uuid.New().String(),
      			},
      		)
      		imageModerationRequest := &green20220302.ImageModerationRequest{
      			//图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
      			//支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
            Service:           tea.String("baselineCheck"),
      			ServiceParameters: tea.String(string(serviceParameters)),
      		}
      
      	return client.ImageModerationWithOptions(imageModerationRequest, runtime)
      
      }
      
      func main() {
      	/**
      	 * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
      	 * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
      	 * 常见获取环境变量方式:
      	 * 获取RAM用户AccessKey ID:os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
      	 * 获取RAM用户AccessKey Secret:os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
      	 */
      	var accessKeyId= "建议从环境变量中获取RAM用户AccessKey ID";
      	var accessKeySecret= "建议从环境变量中获取RAM用户AccessKey Secret";
      	//接入区域和地址请根据实际情况修改
      	var endpoint = "green-cip.cn-shanghai.aliyuncs.com";
      	response,_err := invoke(accessKeyId,accessKeySecret,endpoint)
      	
      	flag := false
      	if _err != nil {
      		var err = &tea.SDKError{}
      		if _t, ok := _err.(*tea.SDKError); ok {
      			err = _t
      			if *err.StatusCode == 500 {
      				flag = true
      			}
      		}
      	}
      	if response == nil || *response.StatusCode == 500 || *response.Body.Code == 500 {
      		flag = true
      	}
          //自动路由,区域切换至cn-beijing。
      	if flag {
      		endpoint = "green-cip.cn-beijing.aliyuncs.com";
      		response, _err = invoke(accessKeyId,accessKeySecret,endpoint)
      	}
      
      	if response != nil {
      		statusCode := tea.IntValue(tea.ToInt(response.StatusCode))
      		body := response.Body
      		imageModerationResponseData := body.Data
      		fmt.Println("requestId:" + tea.StringValue(body.RequestId))
      		if statusCode == http.StatusOK {
      			fmt.Println("response success. response:" + body.String())
      			if tea.IntValue(tea.ToInt(body.Code)) == 200 {
      				result := imageModerationResponseData.Result
      				fmt.Println("response dataId:" + tea.StringValue(imageModerationResponseData.DataId))
      				for i := 0; i < len(result); i++ {
      					fmt.Println("response label:" + tea.StringValue(result[i].Label))
      					fmt.Println("response confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence)))
      				}
      			} else {
      				fmt.Println("image moderation not success. status" + tea.ToString(body.Code))
      			}
      		} else {
      			fmt.Print("response not success. status:" + tea.ToString(statusCode))
      		}
      	}
      }
    • 异步接口接入示例

      提交异步图片检测任务

      package main
      
      import (
      	"encoding/json"
      	"fmt"
      	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      	green20220302 "github.com/alibabacloud-go/green-20220302/client"
      	util "github.com/alibabacloud-go/tea-utils/v2/service"
      	"github.com/alibabacloud-go/tea/tea"
      	"github.com/aliyun/aliyun-oss-go-sdk/oss"
      	"github.com/google/uuid"
      	"net/http"
      	"os"
      	"strings"
      	"time"
      )
      //文件上传token
      var TokenMap =make(map[string]*green20220302.DescribeUploadTokenResponseBodyData)
      //文件上传客户端
      var Bucket *oss.Bucket
      //服务是否部署在VPC上
      var isVPC = false
      //创建请求客户端
      func createClient(accessKeyId string, accessKeySecret string, endpoint string) (*green20220302.Client, error) {
      	config := &openapi.Config{
      		AccessKeyId: tea.String(accessKeyId),
      		AccessKeySecret: tea.String(accessKeySecret),
      		// 设置HTTP代理。
      		// HttpProxy: tea.String("http://10.10.xx.xx:xxxx"),
      		// 设置HTTPS代理。
      		// HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
      		Endpoint: tea.String(endpoint),
      	}
      	//注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
      	return green20220302.NewClient(config);
      }
      
      //创建上传文件客户端
      func createOssClient(tokenData *green20220302.DescribeUploadTokenResponseBodyData) {
      	if isVPC{
      		ossClient, err := oss.New(tea.StringValue(tokenData.OssInternalEndPoint), tea.StringValue(tokenData.AccessKeyId), tea.StringValue(tokenData.AccessKeySecret), oss.SecurityToken(tea.StringValue(tokenData.SecurityToken)))
      		if err != nil {
      			fmt.Println("Error:", err)
      			os.Exit(-1)
      		}
      		Bucket, _ =ossClient.Bucket(tea.StringValue(tokenData.BucketName));
      	}else {
      		ossClient, err := oss.New(tea.StringValue(tokenData.OssInternetEndPoint), tea.StringValue(tokenData.AccessKeyId), tea.StringValue(tokenData.AccessKeySecret), oss.SecurityToken(tea.StringValue(tokenData.SecurityToken)))
      		if err != nil {
      			fmt.Println("Error:", err)
      			os.Exit(-1)
      		}
      		Bucket, _ =ossClient.Bucket(tea.StringValue(tokenData.BucketName));
      	}
      }
      
      //上传文件
      func uploadFile(filePath string,tokenData *green20220302.DescribeUploadTokenResponseBodyData) (string,error) {
      	createOssClient(tokenData)
      	objectName := tea.StringValue(tokenData.FileNamePrefix) + uuid.New().String() + "." + strings.Split(filePath, ".")[1]
      	//上传文件
      	_err := Bucket.PutObjectFromFile(objectName, filePath)
      	if _err != nil {
      		fmt.Println("Error:", _err)
      		os.Exit(-1)
      	}
      	return objectName,_err
      }
      
      func invoke(accessKeyId string, accessKeySecret string, endpoint string) (_result *green20220302.ImageAsyncModerationResponse, _err error) {
      	//注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
      	client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
      	if _err != nil {
      		return nil,_err
      	}
      	//运行时参数设置,仅对使用了该运行时参数实例的请求有效
      	runtime := &util.RuntimeOptions{}
      	//本地文件的完整路径,例如D:\localPath\exampleFile.png。
      	var filePath = "D:\\localPath\\exampleFile.png"
      	//获取文件上传临时token
      	tokenData,ok:=TokenMap[endpoint];
      	if !ok || tea.Int32Value(tokenData.Expiration) <= int32(time.Now().Unix()) {
      		//获取文件上传临时token
      		uploadTokenResponse, _err := client.DescribeUploadToken()
      		if _err != nil {
      			return nil,_err
      		}
      		tokenData = uploadTokenResponse.Body.Data
      		TokenMap[endpoint] = tokenData
      	}
      	var objectName, _ = uploadFile(filePath,TokenMap[endpoint])
      
      	//构建图片检测请求。
      	serviceParameters, _ := json.Marshal(
      		map[string]interface{}{
      			"ossBucketName": tea.StringValue(TokenMap[endpoint].BucketName),
      			"ossObjectName": objectName,
      			"dataId":   uuid.New().String(),
      		},
      	)
      	imageAsyncModerationRequest := &green20220302.ImageAsyncModerationRequest{
      		//图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
      		//支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
      		Service:           tea.String("baselineCheck"),
      		ServiceParameters: tea.String(string(serviceParameters)),
      	}
      
      	return client.ImageAsyncModerationWithOptions(imageAsyncModerationRequest, runtime)
      
      }
      
      func main() {
      	/**
      	 * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
      	 * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
      	 * 常见获取环境变量方式:
      	 * 获取RAM用户AccessKey ID:os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
      	 * 获取RAM用户AccessKey Secret:os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
      	 */
      	var accessKeyId= "建议从环境变量中获取RAM用户AccessKey ID"
      	var accessKeySecret= "建议从环境变量中获取RAM用户AccessKey Secret"
      
      	//接入区域和地址请根据实际情况修改
      	var endpoint = "green-cip.cn-shanghai.aliyuncs.com"
      	response,_err := invoke(accessKeyId,accessKeySecret,endpoint)
      
      	flag := false
      	if _err != nil {
      		var err = &tea.SDKError{}
      		if _t, ok := _err.(*tea.SDKError); ok {
      			err = _t
      			if *err.StatusCode == 500 {
      				flag = true
      			}
      		}
      	}
      	if response == nil || *response.StatusCode == 500 || *response.Body.Code == 500 {
      		flag = true
      	}
      	//自动路由,区域切换至cn-beijing。
      	if flag {
      		endpoint = "green-cip.cn-beijing.aliyuncs.com";
      		response, _err = invoke(accessKeyId,accessKeySecret,endpoint)
      	}
      
      	if response != nil {
      		statusCode := tea.IntValue(tea.ToInt(response.StatusCode))
      		body := response.Body
      		imageAsyncModerationResponseData := body.Data
      		fmt.Println("requestId:" + tea.StringValue(body.RequestId))
      		if statusCode == http.StatusOK {
      			fmt.Println("response success. response:" + body.String())
      			if tea.IntValue(tea.ToInt(body.Code)) == 200 {
      				fmt.Println("response reqId:" + tea.StringValue(imageAsyncModerationResponseData.ReqId))
      
      			} else {
      				fmt.Println("image async moderation not success. status" + tea.ToString(body.Code))
      			}
      		} else {
      			fmt.Print("response not success. status:" + tea.ToString(statusCode))
      		}
      	}
      }

      获取异步图片检测结果

      package main
      
      import (
      	"fmt"
      	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      	green "github.com/alibabacloud-go/green-20220302/client"
      	"github.com/alibabacloud-go/tea/tea"
      )
      
      func main() {
      	config := &openapi.Config{
      		AccessKeyId: tea.String("建议从环境变量中获取RAM用户AccessKey ID"),
      		AccessKeySecret: tea.String("建议从环境变量中获取RAM用户AccessKey Secret"),
      		// 访问的 Endpoint
      		Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"),
      		/**
      		 * 请设置超时时间。服务端全链路处理超时时间为10秒,请做相应设置。
      		 * 如果您设置的ReadTimeout小于服务端处理的时间,程序中会获得一个ReadTimeout异常。
      		 */
      		ConnectTimeout: tea.Int(3000),
      		ReadTimeout:    tea.Int(6000),
      	}
      	client, _err := green.NewClient(config)
      	if _err != nil {
      		panic(_err)
      	}
      
      	request := green.DescribeImageModerationResultRequest{
      		ReqId:           tea.String("F30E5B52-12D7-59BB-95F0-5D3AA08ECABF"),
      	}
      	result, err := client.DescribeImageModerationResult(&request)
      	if err != nil {
      		fmt.Print(err.Error())
      	}
      	fmt.Printf("response is %#v\n", result.Body)
      }
    • service同步接口接入示例

      package main
      
      import (
      	"encoding/json"
      	"fmt"
      	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      	green20220302 "github.com/alibabacloud-go/green-20220302/v2/client"
      	util "github.com/alibabacloud-go/tea-utils/v2/service"
      	"github.com/alibabacloud-go/tea/tea"
      	"github.com/aliyun/aliyun-oss-go-sdk/oss"
      	"github.com/google/uuid"
      	"net/http"
      	"os"
      	"strings"
      	"time"
      )
      //文件上传token
      var TokenMap =make(map[string]*green20220302.DescribeUploadTokenResponseBodyData)
      //文件上传客户端
      var Bucket *oss.Bucket
      //服务是否部署在VPC上
      var isVPC = false
      //创建请求客户端
      func createClient(accessKeyId string, accessKeySecret string, endpoint string) (*green20220302.Client, error) {
      	config := &openapi.Config{
      		AccessKeyId: tea.String(accessKeyId),
      		AccessKeySecret: tea.String(accessKeySecret),
      		// 设置HTTP代理。
      		// HttpProxy: tea.String("http://10.10.xx.xx:xxxx"),
      		// 设置HTTPS代理。
      		// HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
      		Endpoint: tea.String(endpoint),
      	}
      	//注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
      	return green20220302.NewClient(config);
      }
      
      //创建上传文件客户端
      func createOssClient(tokenData *green20220302.DescribeUploadTokenResponseBodyData) {
      	if isVPC{
      		ossClient, err := oss.New(tea.StringValue(tokenData.OssInternalEndPoint), tea.StringValue(tokenData.AccessKeyId), tea.StringValue(tokenData.AccessKeySecret), oss.SecurityToken(tea.StringValue(tokenData.SecurityToken)))
      		if err != nil {
      			fmt.Println("Error:", err)
      			os.Exit(-1)
      		}
      		Bucket, _ =ossClient.Bucket(tea.StringValue(tokenData.BucketName));
      	}else {
      		ossClient, err := oss.New(tea.StringValue(tokenData.OssInternetEndPoint), tea.StringValue(tokenData.AccessKeyId), tea.StringValue(tokenData.AccessKeySecret), oss.SecurityToken(tea.StringValue(tokenData.SecurityToken)))
      		if err != nil {
      			fmt.Println("Error:", err)
      			os.Exit(-1)
      		}
      		Bucket, _ =ossClient.Bucket(tea.StringValue(tokenData.BucketName));
      	}
      }
      
      //上传文件
      func uploadFile(filePath string,tokenData *green20220302.DescribeUploadTokenResponseBodyData) (string,error) {
      	createOssClient(tokenData)
      	objectName := tea.StringValue(tokenData.FileNamePrefix) + uuid.New().String() + "." + strings.Split(filePath, ".")[1]
      	//上传文件
      	_err := Bucket.PutObjectFromFile(objectName, filePath)
      	if _err != nil {
      		fmt.Println("Error:", _err)
      		os.Exit(-1)
      	}
      	return objectName,_err
      }
      
      func invoke(accessKeyId string, accessKeySecret string, endpoint string) (_result *green20220302.ImageBatchModerationResponse, _err error) {
      	//注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
      	client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
      	if _err != nil {
      		return nil,_err
      	}
      	//运行时参数设置,仅对使用了该运行时参数实例的请求有效
      	runtime := &util.RuntimeOptions{}
      	//本地文件的完整路径,例如D:\localPath\exampleFile.png。
      	var filePath = "/Users/admin/test/image/0873.jpg"
      	//获取文件上传临时token
      	tokenData,ok:=TokenMap[endpoint];
      	if !ok || tea.Int32Value(tokenData.Expiration) <= int32(time.Now().Unix()) {
      		//获取文件上传临时token
      		uploadTokenResponse, _err := client.DescribeUploadToken()
      		if _err != nil {
      			return nil,_err
      		}
      		tokenData = uploadTokenResponse.Body.Data
      		TokenMap[endpoint] = tokenData
      	}
      	var objectName, _ = uploadFile(filePath,TokenMap[endpoint])
      
      	//构建图片检测请求。
      	serviceParameters, _ := json.Marshal(
      		map[string]interface{}{
      			"ossBucketName": tea.StringValue(TokenMap[endpoint].BucketName),
      			"ossObjectName": objectName,
      			"dataId":   uuid.New().String(),
      		},
      	)
      	imageBatchModerationRequest := &green20220302.ImageBatchModerationRequest{
      		//图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
      		Service:           tea.String("baselineCheck,profilePhotoCheck"),
      		ServiceParameters: tea.String(string(serviceParameters)),
      	}
      
      	return client.ImageBatchModerationWithOptions(imageBatchModerationRequest, runtime)
      
      }
      
      func main() {
      	/**
      	 * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
      	 * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
      	 * 常见获取环境变量方式:
      	 * 获取RAM用户AccessKey ID:os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
      	 * 获取RAM用户AccessKey Secret:os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
      	 */
      	var accessKeyId= "建议从环境变量中获取RAM用户AccessKey ID"
      	var accessKeySecret= "建议从环境变量中获取RAM用户AccessKey Secret"
      	//接入区域和地址请根据实际情况修改
      	var endpoint = "green-cip.cn-shanghai.aliyuncs.com"
      	response,_err := invoke(accessKeyId,accessKeySecret,endpoint)
      
      	flag := false
      	if _err != nil {
      		var err = &tea.SDKError{}
      		if _t, ok := _err.(*tea.SDKError); ok {
      			err = _t
      			if *err.StatusCode == 500 {
      				flag = true
      			}
      		}
      	}
      	if response == nil || *response.StatusCode == 500 || *response.Body.Code == 500 {
      		flag = true
      	}
      	//自动路由,区域切换至cn-beijing。
      	if flag {
      		endpoint = "green-cip.cn-beijing.aliyuncs.com";
      		response, _err = invoke(accessKeyId,accessKeySecret,endpoint)
      	}
      
      	if response != nil {
      		statusCode := tea.IntValue(tea.ToInt(response.StatusCode))
      		body := response.Body
      		imageBatchModerationResponseData := body.Data
      		fmt.Println("requestId:" + tea.StringValue(body.RequestId))
      		if statusCode == http.StatusOK {
      			fmt.Println("response success. response:" + body.String())
      			if tea.IntValue(tea.ToInt(body.Code)) == 200 {
      				result := imageBatchModerationResponseData.Result
      				fmt.Println("response dataId:" + tea.StringValue(imageBatchModerationResponseData.DataId))
      				for i := 0; i < len(result); i++ {
      					fmt.Println("response label:" + tea.StringValue(result[i].Label))
      					fmt.Println("response confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence)))
      				}
      			} else {
      				fmt.Println("image moderation not success. status" + tea.ToString(body.Code))
      			}
      		} else {
      			fmt.Print("response not success. status:" + tea.ToString(statusCode))
      		}
      	}
      }
      

OSS图片进行检测

使用场景

如果您需要审核的图片文件已经存储在阿里云对象存储OSS中,你可授权创建服务角色,允许内容安全服务访问对象存储OSS。图片审核增强版服务会通过服务角色获取到对象存储OSS的文件后进行审核。访问云资源访问授权页面创建服务角色。

  1. 使用阿里云账号(即主账号)访问云资源访问授权页面进行授权。

  2. 执行如下命令安装Go SDK。

    go get github.com/alibabacloud-go/green-20220302/v2
  3. 接入Go SDK。

    • 同步接口接入示例

      package main
      
      import (
      	"encoding/json"
      	"fmt"
      	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      	green20220302 "github.com/alibabacloud-go/green-20220302/client"
      	util "github.com/alibabacloud-go/tea-utils/v2/service"
      	"github.com/alibabacloud-go/tea/tea"
      	"github.com/google/uuid"
      	"net/http"
      	"os"
      )
      
      //创建请求客户端
      func createClient(accessKeyId *string, accessKeySecret *string, endpoint *string) (*green20220302.Client, error) {
      	config := &openapi.Config{
      		AccessKeyId: accessKeyId,
      		AccessKeySecret: accessKeySecret,
      		// 设置HTTP代理。
      		// HttpProxy: tea.String("http://10.10.xx.xx:xxxx"),
      		// 设置HTTPS代理。
      		// HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
      		Endpoint: endpoint,
      	}
      	//注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
      	return green20220302.NewClient(config);
      }
      
      func invoke(accessKeyId *string, accessKeySecret *string, endpoint *string) (_result *green20220302.ImageModerationResponse, _err error) {
      	//注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
      	client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
      	if _err != nil {
      		return nil,_err
      	}
      	//运行时参数设置,仅对使用了该运行时参数实例的请求有效
      	runtime := &util.RuntimeOptions{}
      
      	//构建图片检测请求。
      		serviceParameters, _ := json.Marshal(
      			map[string]interface{}{
      				//待检测图片的OSSbucket所在region。示例:cn-shanghai
      				"ossRegionId": "cn-shanghai",
      				//待检测图片的OSSbucket名称。示例:bucket001
      				"ossBucketName":"bucket001",
      				//待检测图片的Object名称。示例:image/001.jpg
      				"ossObjectName":"image/001.jpg",
      				//待检测数据的ID。
      				"dataId":   uuid.New().String(),
      			},
      		)
      		imageModerationRequest := &green20220302.ImageModerationRequest{
      			//图片检测service,用户控制台图片增强版规则配置的serviceCode 示例: baselineCheck
      			//支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
            Service:           tea.String("baselineCheck"),
      			ServiceParameters: tea.String(string(serviceParameters)),
      		}
      
      	return client.ImageModerationWithOptions(imageModerationRequest, runtime)
      
      }
      
      func main() {
      	/**
      	 * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
      	 * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
      	 * 常见获取环境变量方式:
      	 * 获取RAM用户AccessKey ID:os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
      	 * 获取RAM用户AccessKey Secret:os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
      	 */
      	var accessKeyId= tea.String("建议从环境变量中获取RAM用户AccessKey ID");
      	var accessKeySecret= tea.String("建议从环境变量中获取RAM用户AccessKey Secret");
      	//接入区域和地址请根据实际情况修改
      	var endpoint = tea.String("green-cip.cn-shanghai.aliyuncs.com");
      	response,_err := invoke(accessKeyId,accessKeySecret,endpoint)
      	//自动路由,区域切换至cn-beijing。
      	flag := false
      	if _err != nil {
      		var err = &tea.SDKError{}
      		if _t, ok := _err.(*tea.SDKError); ok {
      			err = _t
      			// 系统异常,切换到下个地域调用。
      			if *err.StatusCode == 500 {
      				flag = true
      			}
      		}
      	}
      	if response == nil || *response.StatusCode == 500 || *response.Body.Code == 500 {
      		flag = true
      	}
      	if flag {
      		endpoint = tea.String("green-cip.cn-beijing.aliyuncs.com");
      		response, _err = invoke(accessKeyId,accessKeySecret,endpoint)
      	}
      
      	if response != nil {
      		statusCode := tea.IntValue(tea.ToInt(response.StatusCode))
      		body := response.Body
      		imageModerationResponseData := body.Data
      		fmt.Println("requestId:" + tea.StringValue(body.RequestId))
      		if statusCode == http.StatusOK {
      			fmt.Println("response success. response:" + body.String())
      			if tea.IntValue(tea.ToInt(body.Code)) == 200 {
      				result := imageModerationResponseData.Result
      				fmt.Println("response dataId:" + tea.StringValue(imageModerationResponseData.DataId))
      				for i := 0; i < len(result); i++ {
      					fmt.Println("response label:" + tea.StringValue(result[i].Label))
      					fmt.Println("response confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence)))
      				}
      			} else {
      				fmt.Println("image moderation not success. status" + tea.ToString(body.Code))
      			}
      		} else {
      			fmt.Print("response not success. status:" + tea.ToString(statusCode))
      		}
      	}
      }
    • 异步接口接入示例

      提交异步图片检测任务

      package main
      
      import (
      	"encoding/json"
      	"fmt"
      	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      	green "github.com/alibabacloud-go/green-20220302/client"
      	"github.com/alibabacloud-go/tea/tea"
      )
      
      func main() {
      	config := &openapi.Config{
      		AccessKeyId: tea.String("建议从环境变量中获取RAM用户AccessKey ID"),
      		AccessKeySecret: tea.String("建议从环境变量中获取RAM用户AccessKey Secret"),
      		// 访问的 Endpoint
      		Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"),
      		/**
      		 * 请设置超时时间。服务端全链路处理超时时间为10秒,请做相应设置。
      		 * 如果您设置的ReadTimeout小于服务端处理的时间,程序中会获得一个ReadTimeout异常。
      		 */
      		ConnectTimeout: tea.Int(3000),
      		ReadTimeout:    tea.Int(6000),
      	}
      	client, _err := green.NewClient(config)
      	if _err != nil {
      		panic(_err)
      	}
      
      	serviceParameters, _ := json.Marshal(
      		map[string]interface{}{
      		//待检测图片的OSSbucket所在region。示例:cn-shanghai
      	    "ossRegionId": "cn-shanghai",
      	    //待检测图片的OSSbucket名称。示例:bucket001
      	    "ossBucketName":"bucket001",
      	    //待检测图片的Object名称。示例:image/001.jpg
      	    "ossObjectName":"image/001.jpg",
      	    //待检测数据的ID。
      	    "dataId":   uuid.New().String(),
      		},
      	)
      	request := green.ImageAsyncModerationRequest{
      		Service:           tea.String("baselineCheck"),
      		ServiceParameters: tea.String(string(serviceParameters)),
      	}
      	result, err := client.ImageAsyncModeration(&request)
      	if err != nil {
      		fmt.Print(err.Error())
      	}
      	fmt.Printf("response is %#v\n", result.Body)
      }
      

      获取异步图片检测结果

      package main
      
      import (
      	"fmt"
      	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      	green "github.com/alibabacloud-go/green-20220302/client"
      	"github.com/alibabacloud-go/tea/tea"
      )
      
      func main() {
      	config := &openapi.Config{
      		AccessKeyId: tea.String("建议从环境变量中获取RAM用户AccessKey ID"),
      		AccessKeySecret: tea.String("建议从环境变量中获取RAM用户AccessKey Secret"),
      		// 访问的 Endpoint
      		Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"),
      		/**
      		 * 请设置超时时间。服务端全链路处理超时时间为10秒,请做相应设置。
      		 * 如果您设置的ReadTimeout小于服务端处理的时间,程序中会获得一个ReadTimeout异常。
      		 */
      		ConnectTimeout: tea.Int(3000),
      		ReadTimeout:    tea.Int(6000),
      	}
      	client, _err := green.NewClient(config)
      	if _err != nil {
      		panic(_err)
      	}
      
      	request := green.DescribeImageModerationResultRequest{
      		ReqId:           tea.String("F30E5B52-12D7-59BB-95F0-5D3AA08ECABF"),
      	}
      	result, err := client.DescribeImageModerationResult(&request)
      	if err != nil {
      		fmt.Print(err.Error())
      	}
      	fmt.Printf("response is %#v\n", result.Body)
      }
    • service同步接口接入示例

      package main
      
      import (
         "encoding/json"
         "fmt"
         openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
         green20220302 "github.com/alibabacloud-go/green-20220302/v2/client"
         util "github.com/alibabacloud-go/tea-utils/v2/service"
         "github.com/alibabacloud-go/tea/tea"
         "github.com/google/uuid"
      )
      
      // 创建请求客户端
      func createClient(accessKeyId *string, accessKeySecret *string, endpoint *string) (*green20220302.Client, error) {
         config := &openapi.Config{
            AccessKeyId: accessKeyId,
            AccessKeySecret: accessKeySecret,
            Endpoint: endpoint,
         }
         return green20220302.NewClient(config)
      }
      
      func invoke(accessKeyId *string, accessKeySecret *string, endpoint *string) (_result *green20220302.ImageBatchModerationResponse, _err error) {
         client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
         if _err != nil {
            return nil, _err
         }
         runtime := &util.RuntimeOptions{}
         serviceParameters, _ := json.Marshal(
            map[string]interface{}{
      	 "ossRegionId": "cn-shanghai",
      	 //待检测图片的OSSbucket名称。示例:bucket001
      	 "ossBucketName":"bucket001",
      	 //待检测图片的Object名称。示例:image/001.jpg
      	 "ossObjectName":"image/001.jpg",
               //待检测数据的ID。
               "dataId": uuid.New(),
            },
         )
      
         ImageBatchModerationRequest := &green20220302.ImageBatchModerationRequest{
            Service:tea.String("baselineCheck,baselineCheck_pro"),
            ServiceParameters: tea.String(string(serviceParameters)),
         }
      
         return client.ImageBatchModerationWithOptions(ImageBatchModerationRequest, runtime)
      
      }
      
      func main() {
         var accessKeyId = tea.String("建议从环境变量中获取RAM用户AccessKey ID")
         var accessKeySecret = tea.String("建议从环境变量中获取RAM用户AccessKey Secret")
         var endpoint = tea.String("green-cip.cn-shanghai.aliyuncs.com")
         response, _err := invoke(accessKeyId, accessKeySecret, endpoint)
         if _err != nil {
            return;
         }
         if response != nil {
            statusCode := tea.IntValue(tea.ToInt(response.StatusCode))
            body := response.Body
            imageBatchModerationResponseData := body.Data
            fmt.Println("requestId:" + tea.StringValue(body.RequestId))
            if statusCode == 200 {
               fmt.Println("response success. response:" + body.String())
               if tea.IntValue(tea.ToInt(body.Code)) == 200 {
                  result := imageBatchModerationResponseData.Result
                  fmt.Println("response dataId:" + tea.StringValue(imageBatchModerationResponseData.DataId))
                  for i := 0; i < len(result); i++ {
                     fmt.Println("response label:" + tea.StringValue(result[i].Label))
                     fmt.Println("response confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence)))
                  }
               } else {
                  fmt.Println("image moderation not success. status" + tea.ToString(body.Code))
               }
            } else {
               fmt.Print("response not success. status:" + tea.ToString(statusCode))
            }
         }
      }
      

Node.js SDK

原始代码,请参见Node.js SDK源码

支持以下三种类型的图片检测。

对公网可访问图片进行检测

使用场景

当需要审核的图片可通过公网链接访问时,图片审核增强版服务可通过图片URL获取文件后进行审核。

  1. 安装Node.js SDK。

    执行如下命令引入相关依赖。

    npm install @alicloud/green20220302@2.19.1
  2. 接入Node.js SDK。

    • 同步接口接入示例

      const RPCClient = require("@alicloud/pop-core");
      const { v4: uuidv4 } = require('uuid');
      
      async function main() {
          // 注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
          var client = new RPCClient({
      				/**
               * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
               * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
               * 常见获取环境变量方式:
               * 获取RAM用户AccessKey ID:process.env['ALIBABA_CLOUD_ACCESS_KEY_ID']
               * 获取RAM用户AccessKey Secret:process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
               */
              accessKeyId: '建议从环境变量中获取RAM用户AccessKey ID',
              accessKeySecret: '建议从环境变量中获取RAM用户AccessKey Secret',
              // 接入区域和地址请根据实际情况修改
              endpoint: "https://green-cip.cn-shanghai.aliyuncs.com",
              apiVersion: '2022-03-02',
              // 设置http代理
              // httpProxy: "http://xx.xx.xx.xx:xxxx",
              // 设置https代理
              // httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999",
          });
          // 通过以下代码创建API请求并设置参数。
          var params = {
              // 图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
              // 支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
              "Service": "baselineCheck",
              "ServiceParameters": JSON.stringify({
                  //数据ID唯一标识
                  "dataId": uuidv4(),
                  //待检测图片链接, 公网可访问。
                  "imageUrl": "https://img.alicdn.com/tfs/xxxxxxxxxx001.png"
              })
          }
      
          var requestOption = {
              method: 'POST',
              formatParams: false,
          };
      
          try {
              //调用接口获取检测结果。
              var response = await client.request('ImageModeration', params, requestOption)
              //自动路由。
              if (response.Code === 500) {
                  //区域切换到cn-beijing。
                  client.endpoint = "https://green-cip.cn-beijing.aliyuncs.com"
                  response = await client.request('ImageModeration', params, requestOption)
              }
          } catch (err) {
              console.log(err);
          }
      
          return response;
      }
      
      main().then(function (response) {
          console.log(JSON.stringify(response))
      });
    • 异步接口接入示例

      提交异步图片检测任务

      const Green20220302 = require('@alicloud/green20220302');
      const OpenApi = require('@alicloud/openapi-client');
      const Util = require('@alicloud/tea-util');
      // 注意:此处实例化的client尽可能重复使用,提升检测性能。避免重复建立连接。
      // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
      class Client {
          static createClient() {
              const config = new OpenApi.Config({
                  // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                  // accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                  // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                  // accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                  endpoint: `green-cip.cn-shanghai.aliyuncs.com`,
              });
              return new Green20220302.default(config);
          }
      
          static async main() {
              const client = Client.createClient();
              // 构造请求对象
              const imageAsyncModerationRequest = new Green20220302.ImageAsyncModerationRequest({
                  "service": "baselineCheck",
                  "serviceParameters": JSON.stringify({"imageurl":"http://www.aliyun.com/test.jpg"})
              });
              // 创建运行时配置对象
              const runtime = new Util.RuntimeOptions();
              try {
                  // 发起请求并获取响应
                  const response = await client.imageAsyncModerationWithOptions(imageAsyncModerationRequest, runtime);
                  console.log(JSON.stringify(response.body));
              } catch (error) {
                  // 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
                  // 错误 message
                  console.log('Error occurred:', error.message);
              }
          }
      }
      
      Client.main();

      获取异步图片检测结果

      const Green20220302 = require('@alicloud/green20220302');
      const OpenApi = require('@alicloud/openapi-client');
      const Util = require('@alicloud/tea-util');
      // 注意:此处实例化的client尽可能重复使用,提升检测性能。避免重复建立连接。
      // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
      class Client {
          static createClient() {
              const config = new OpenApi.Config({
                  // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                  accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                  // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                  accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                  endpoint: `green-cip.cn-shanghai.aliyuncs.com`,
              });
              return new Green20220302.default(config);
          }
      
          static async main() {
              const client = Client.createClient();
              // 构造请求对象
              const describeImageModerationResultRequest = new Green20220302.DescribeImageModerationResultRequest({
                  "reqId": "5B61EF1B-FF90-5264-8083-9FA75E955E01",
              });
              // 创建运行时配置对象
              const runtime = new Util.RuntimeOptions();
              try {
                  // 发起请求并获取响应
                  const response = await client.describeImageModerationResultWithOptions(describeImageModerationResultRequest, runtime);
                  console.log(JSON.stringify(response.body));
              } catch (error) {
                  // 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
                  // 错误 message
                  console.log('Error occurred:', error.message);
              }
          }
      }
      
      Client.main();
    • service同步接口接入示例

      const Green20220302 = require('@alicloud/green20220302');
      const OpenApi = require('@alicloud/openapi-client');
      const Util = require('@alicloud/tea-util');
      // 注意:此处实例化的client尽可能重复使用,提升检测性能。避免重复建立连接。
      // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
      class Client {
          static createClient() {
              const config = new OpenApi.Config({
                  // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                  // accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                  // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                  // accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                  endpoint: `green-cip.cn-shanghai.aliyuncs.com`,
              });
              return new Green20220302.default(config);
          }
      
          static async main() {
              const client = Client.createClient();
              // 构造请求对象
              const imageBatchModerationRequest = new Green20220302.ImageBatchModerationRequest({
                  "service": "baselineCheck,profilePhotoCheck",
                  "serviceParameters": JSON.stringify({"imageurl":"http://www.aliyun.com/test.jpg"})
              });
              // 创建运行时配置对象
              const runtime = new Util.RuntimeOptions();
              try {
                  // 发起请求并获取响应
                  const response = await client.imageBatchModerationWithOptions(imageBatchModerationRequest, runtime);
                  console.log(JSON.stringify(response.body));
              } catch (error) {
                  // 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
                  // 错误 message
                  console.log('Error occurred:', error.message);
              }
          }
      }
      
      Client.main();

对本地图片进行检测

使用场景

当您需要审核的图片在本地机器且无公网访问链接,您可以将图片上传到内容安全提供的对象存储OSS Bucket中,图片审核增强版服务可直接访问对象存储OSS,获取到图片内容后进行审核。

  1. 安装Node.js SDK。

    安装内容安全SDK:

    npm install @alicloud/green20220302@2.19.1

    安装OSS依赖:

    npm install ali-oss --save
  2. 接入Node.js SDK。

    • 同步接口接入示例

      const RPCClient = require("@alicloud/pop-core");
      const OSS = require('ali-oss');
      const { v4: uuidv4 } = require('uuid');
      const path = require("path");
      
      //服务是否部署在VPC上
      var isVPC = false;
      //文件上传token
      var tokenDic = new Array();
      //文件上传客户端
      var ossClient;
      
      //创建文件上传客户端
      function createClient(accessKeyId, accessKeySecret, endpoint) {
          return new RPCClient({
              accessKeyId: accessKeyId,
              accessKeySecret: accessKeySecret,
              endpoint: endpoint,
              apiVersion: '2022-03-02',
              //设置http代理
              //httpProxy: "http://xx.xx.xx.xx:xxxx",
              //设置https代理
              //httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999",
          });
      }
      
      //创建文件上传客户端
      function getOssClient(tokenData, isVPC) {
          if (isVPC) {
              ossClient = new OSS({
                  accessKeyId: tokenData['AccessKeyId'],
                  accessKeySecret: tokenData['AccessKeySecret'],
                  stsToken: tokenData['SecurityToken'],
                  endpoint: tokenData['OssInternalEndPoint'],
                  bucket: tokenData['BucketName'],
              });
          } else {
              ossClient = new OSS({
                  accessKeyId: tokenData['AccessKeyId'],
                  accessKeySecret: tokenData['AccessKeySecret'],
                  stsToken: tokenData['SecurityToken'],
                  endpoint: tokenData['OssInternetEndPoint'],
                  bucket: tokenData['BucketName'],
              });
          }
      }
      
      //提交检测任务
      async function invoke(accessKeyId, accessKeySecret, endpoint) {
          //注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
          var client = createClient(accessKeyId, accessKeySecret, endpoint);
          var requestOption = {
              method: 'POST',
              formatParams: false,
          };
          //本地文件的完整路径,例如D:\\localPath\\exampleFile.png。
          var filePath = 'D:\\localPath\\exampleFile.png';
      
          //获取上传文件token
          if (tokenDic[endpoint] == null || tokenDic[endpoint]['Expiration'] <= Date.parse(new Date() / 1000)) {
              var tokenResponse = await client.request('DescribeUploadToken', '', requestOption)
              tokenDic[endpoint] = tokenResponse.Data;
          }
      
          //获取上传文件客户端
          getOssClient(tokenDic[endpoint], isVPC)
          var split = filePath.split(".");
          var objectName;
          if (split.length > 1) {
              objectName = tokenDic[endpoint].FileNamePrefix + uuidv4() + "." + split[split.length - 1];
          } else {
              objectName = tokenDic[endpoint].FileNamePrefix + uuidv4();
          }
          //上传文件
          const result = await ossClient.put(objectName, path.normalize(filePath));
      
          //通过以下代码创建检测API请求并设置参数。
          var params = {
              //图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
              //支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
              "Service": "baselineCheck",
              //本地图片上传信息
              "ServiceParameters": JSON.stringify({
                  "ossBucketName": tokenDic[endpoint].BucketName,
                  "ossObjectName": objectName
              })
          }
          //调用接口获取检测结果
          return await client.request('ImageModeration', params, requestOption);
      }
      
      
      
      function main() {
      	/**
          * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
          * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
          * 常见获取环境变量方式:
          * 获取RAM用户AccessKey ID:process.env['ALIBABA_CLOUD_ACCESS_KEY_ID']
          * 获取RAM用户AccessKey Secret:process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
          */
          const accessKeyId: '建议从环境变量中获取RAM用户AccessKey ID'
          const accessKeySecret: '建议从环境变量中获取RAM用户AccessKey Secret'
          //接入区域和地址请根据实际情况修改
          var endpoint = "https://green-cip.cn-shanghai.aliyuncs.com"
      
          try {
              var response;
              //调用接口获取检测结果
              invoke(accessKeyId, accessKeySecret, endpoint).then(function (response) {
                  //自动路由
                  if (response.Code == 500) {
                      //区域切换到cn-beijing。
                      endpoint = "https://green-cip.cn-beijing.aliyuncs.com"
                      invoke(accessKeyId, accessKeySecret, endpoint).then(function (response){
                          console.log(JSON.stringify(response))
                      })
                  }else{
                      console.log(JSON.stringify(response))
                  }
              })
          } catch (err) {
              console.log(err);
          }
      }
      
      main();
    • 异步接口接入示例

      提交异步图片检测任务

      const Green20220302 = require('@alicloud/green20220302');
      const OpenApi = require('@alicloud/openapi-client');
      const { v4: uuidv4 } = require('uuid');
      const OSS = require('ali-oss');
      const Util = require('@alicloud/tea-util');
      const path = require("path");
      // 注意:此处实例化的client尽可能重复使用,提升检测性能。避免重复建立连接。
      // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
      
      //服务是否部署在VPC上
      var isVPC = false;
      //文件上传token
      var tokenDic = new Array();
      //文件上传客户端
      var ossClient;
      var endpoint = 'green-cip.cn-shanghai.aliyuncs.com'
      var filePath = '/Users/Documents/test/11.jpg'
      var service = 'baselineCheck'
      
      class Client {
          static createClient() {
              const config = new OpenApi.Config({
                  // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                  accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                  // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                  accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                  endpoint: endpoint,
              });
              return new Green20220302.default(config);
          }
      
          //创建文件上传客户端
          static getOssClient(tokenData, isVPC) {
              if (isVPC) {
                  ossClient = new OSS({
                      accessKeyId: tokenData['accessKeyId'],
                      accessKeySecret: tokenData['accessKeySecret'],
                      stsToken: tokenData['securityToken'],
                      endpoint: tokenData['ossInternalEndPoint'],
                      bucket: tokenData['bucketName'],
                  });
              } else {
                  ossClient = new OSS({
                      accessKeyId: tokenData['accessKeyId'],
                      accessKeySecret: tokenData['accessKeySecret'],
                      stsToken: tokenData['securityToken'],
                      endpoint: tokenData['ossInternetEndPoint'],
                      bucket: tokenData['bucketName'],
                  });
              }
          }
      
          static async main() {
              const client = Client.createClient();
              // 创建运行时配置对象
              const runtime = new Util.RuntimeOptions();
              
              //获取上传文件token
              if (tokenDic[endpoint] == null || tokenDic[endpoint]['expiration'] <= Date.parse(new Date() / 1000)) {
                  var tokenResponse = await client.describeUploadTokenWithOptions(runtime)
                  tokenDic[endpoint] = tokenResponse.body.data;
              }
      
              //获取上传文件客户端
          this.getOssClient(tokenDic[endpoint], isVPC)
              var split = filePath.split(".");
              var objectName;
              if (split.length > 1) {
                  objectName = tokenDic[endpoint].fileNamePrefix + uuidv4() + "." + split[split.length - 1];
              } else {
                  objectName = tokenDic[endpoint].fileNamePrefix + uuidv4();
              }
      
              //上传文件
              const result = await ossClient.put(objectName, path.normalize(filePath));
      
              // 构造请求对象
              const imageAsyncModerationRequest = new Green20220302.ImageAsyncModerationRequest({
                  // 检测service。
                  "service": service,
                  // 待检测链接。
                  "serviceParameters": JSON.stringify({
                      "ossBucketName": tokenDic[endpoint].bucketName,
                      "ossObjectName": objectName,
                  })
                  });
      
              try {
                  // 发起请求并获取响应
                  const response = await client.imageAsyncModerationWithOptions(imageAsyncModerationRequest, runtime);
                  console.log(JSON.stringify(response.body));
              } catch (error) {
                  // 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
                  // 错误 message
                  console.log('Error occurred:', error.message);
              }
          }
      }
      
      Client.main();

      获取异步图片检测结果

      const Green20220302 = require('@alicloud/green20220302');
      const OpenApi = require('@alicloud/openapi-client');
      const Util = require('@alicloud/tea-util');
      // 注意:此处实例化的client尽可能重复使用,提升检测性能。避免重复建立连接。
      // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
      class Client {
          static createClient() {
              const config = new OpenApi.Config({
                  // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                  accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                  // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                  accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                  endpoint: `green-cip.cn-shanghai.aliyuncs.com`,
              });
              return new Green20220302.default(config);
          }
      
          static async main() {
              const client = Client.createClient();
              // 构造请求对象
              const describeImageModerationResultRequest = new Green20220302.DescribeImageModerationResultRequest({
                  "reqId": "5B61EF1B-FF90-5264-8083-9FA75E955E01",
              });
              // 创建运行时配置对象
              const runtime = new Util.RuntimeOptions();
              try {
                  // 发起请求并获取响应
                  const response = await client.describeImageModerationResultWithOptions(describeImageModerationResultRequest, runtime);
                  console.log(JSON.stringify(response.body));
              } catch (error) {
                  // 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
                  // 错误 message
                  console.log('Error occurred:', error.message);
              }
          }
      }
      
      Client.main();
    • service同步接口接入示例

      const Green20220302 = require('@alicloud/green20220302');
      const OpenApi = require('@alicloud/openapi-client');
      const { v4: uuidv4 } = require('uuid');
      const OSS = require('ali-oss');
      const Util = require('@alicloud/tea-util');
      const path = require("path");
      // 注意:此处实例化的client尽可能重复使用,提升检测性能。避免重复建立连接。
      // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
      
      //服务是否部署在VPC上
      var isVPC = false;
      //文件上传token
      var tokenDic = new Array();
      //文件上传客户端
      var ossClient;
      var endpoint = 'green-cip.cn-shanghai.aliyuncs.com'
      var filePath = '/Users/admin/test/image/0873.jpg'
      var service = 'baselineCheck,profilePhotoCheck'
      
      class Client {
          static createClient() {
              const config = new OpenApi.Config({
                  // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                  accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                  // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                  accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                  endpoint: endpoint,
              });
              return new Green20220302.default(config);
          }
      
          //创建文件上传客户端
          static getOssClient(tokenData, isVPC) {
              if (isVPC) {
                  ossClient = new OSS({
                      accessKeyId: tokenData['accessKeyId'],
                      accessKeySecret: tokenData['accessKeySecret'],
                      stsToken: tokenData['securityToken'],
                      endpoint: tokenData['ossInternalEndPoint'],
                      bucket: tokenData['bucketName'],
                  });
              } else {
                  ossClient = new OSS({
                      accessKeyId: tokenData['accessKeyId'],
                      accessKeySecret: tokenData['accessKeySecret'],
                      stsToken: tokenData['securityToken'],
                      endpoint: tokenData['ossInternetEndPoint'],
                      bucket: tokenData['bucketName'],
                  });
              }
          }
      
          static async main() {
              const client = Client.createClient();
              // 创建运行时配置对象
              const runtime = new Util.RuntimeOptions();
              
              //获取上传文件token
              if (tokenDic[endpoint] == null || tokenDic[endpoint]['expiration'] <= Date.parse(new Date() / 1000)) {
                  var tokenResponse = await client.describeUploadTokenWithOptions(runtime)
                  tokenDic[endpoint] = tokenResponse.body.data;
              }
      
              //获取上传文件客户端
          this.getOssClient(tokenDic[endpoint], isVPC)
              var split = filePath.split(".");
              var objectName;
              if (split.length > 1) {
                  objectName = tokenDic[endpoint].fileNamePrefix + uuidv4() + "." + split[split.length - 1];
              } else {
                  objectName = tokenDic[endpoint].fileNamePrefix + uuidv4();
              }
      
              //上传文件
              const result = await ossClient.put(objectName, path.normalize(filePath));
      
              // 构造请求对象
              const imageBatchModerationRequest = new Green20220302.ImageBatchModerationRequest({
                  // 检测service。
                  "service": service,
                  // 待检测链接。
                  "serviceParameters": JSON.stringify({
                      "ossBucketName": tokenDic[endpoint].bucketName,
                      "ossObjectName": objectName,
                  })
                  });
      
              try {
                  // 发起请求并获取响应
                  const response = await client.imageBatchModerationWithOptions(imageBatchModerationRequest, runtime);
                  console.log(JSON.stringify(response.body));
              } catch (error) {
                  // 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
                  // 错误 message
                  console.log('Error occurred:', error.message);
              }
          }
      }
      
      Client.main();

OSS图片进行检测

使用场景

如果您需要审核的图片文件已经存储在阿里云对象存储OSS中,你可授权创建服务角色,允许内容安全服务访问对象存储OSS。图片审核增强版服务会通过服务角色获取到对象存储OSS的文件后进行审核。访问云资源访问授权页面创建服务角色。

  1. 使用阿里云账号(即主账号)访问云资源访问授权页面进行授权。

  2. 安装Node.js SDK。

    npm install @alicloud/green20220302@2.19.1
  3. 接入Node.js SDK。

    • 同步接口接入示例

      const RPCClient = require("@alicloud/pop-core");
      const { v4: uuidv4 } = require('uuid');
      
      async function main() {
          // 注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
          var client = new RPCClient({
      				/**
               * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
               * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
               * 常见获取环境变量方式:
               * 获取RAM用户AccessKey ID:process.env['ALIBABA_CLOUD_ACCESS_KEY_ID']
               * 获取RAM用户AccessKey Secret:process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
               */
              accessKeyId: '建议从环境变量中获取RAM用户AccessKey ID',
              accessKeySecret: '建议从环境变量中获取RAM用户AccessKey Secret',
              // 接入区域和地址请根据实际情况修改
              endpoint: "https://green-cip.cn-shanghai.aliyuncs.com",
              apiVersion: '2022-03-02',
              // 设置http代理
              // httpProxy: "http://xx.xx.xx.xx:xxxx",
              // 设置https代理
              // httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999",
          });
      
          // 通过以下代码创建API请求并设置参数。
          var params = {
              // 图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
              // 支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
              "Service": "baselineCheck",
              // 待检测图片Oss信息
              "ServiceParameters": JSON.stringify({
                  // 待检测文件所在bucket的区域。 示例:cn-shanghai
                  "ossRegionId": "cn-shanghai",
                  // 待检测文件所在bucket名称。示例:bucket001
                  "ossBucketName": "bucket001",
                  // 待检测文件。 示例:image/001.jpg
                  "ossObjectName": "image/001.jpg",
                  // 数据唯一标识
                  "dataId": uuidv4()
              })
          }
      
          var requestOption = {
              method: 'POST',
              formatParams: false,
          };
      
          try {
              //调用接口获取检测结果。
              var response = await client.request('ImageModeration', params, requestOption)
              //自动路由。
              if (response.Code === 500) {
                  //区域切换到cn-beijing。
                  client.endpoint = "https://green-cip.cn-beijing.aliyuncs.com"
                  response = await client.request('ImageModeration', params, requestOption)
              }
              return response;
          } catch (err) {
              console.log(err);
          }
      }
      
      main().then(function (response) {
          console.log(JSON.stringify(response))
      });
    • 异步接口接入示例

      提交异步图片检测任务

      const Green20220302 = require('@alicloud/green20220302');
      const OpenApi = require('@alicloud/openapi-client');
      const Util = require('@alicloud/tea-util');
      // 注意:此处实例化的client尽可能重复使用,提升检测性能。避免重复建立连接。
      // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
      class Client {
          static createClient() {
              const config = new OpenApi.Config({
                  // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                  // accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                  // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                  // accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                  endpoint: `green-cip.cn-shanghai.aliyuncs.com`,
              });
              return new Green20220302.default(config);
          }
      
          static async main() {
              const client = Client.createClient();
              // 构造请求对象
              const imageAsyncModerationRequest = new Green20220302.ImageAsyncModerationRequest({
                  "service": "baselineCheck",
                  "serviceParameters": JSON.stringify({
                   // 待检测文件所在bucket的区域。 示例:cn-shanghai
                  "ossRegionId": "cn-shanghai",
                  // 待检测文件所在bucket名称。示例:bucket001
                  "ossBucketName": "bucket001",
                  // 待检测文件。 示例:image/001.jpg
                  "ossObjectName": "image/001.jpg",
                  // 数据唯一标识
                  "dataId": uuidv4()
                  })
              });
              // 创建运行时配置对象
              const runtime = new Util.RuntimeOptions();
              try {
                  // 发起请求并获取响应
                  const response = await client.imageAsyncModerationWithOptions(imageAsyncModerationRequest, runtime);
                  console.log(JSON.stringify(response.body));
              } catch (error) {
                  // 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
                  // 错误 message
                  console.log('Error occurred:', error.message);
              }
          }
      }
      
      Client.main();

      获取异步图片检测结果

      const Green20220302 = require('@alicloud/green20220302');
      const OpenApi = require('@alicloud/openapi-client');
      const Util = require('@alicloud/tea-util');
      // 注意:此处实例化的client尽可能重复使用,提升检测性能。避免重复建立连接。
      // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
      class Client {
          static createClient() {
              const config = new OpenApi.Config({
                  // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                  accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                  // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                  accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                  endpoint: `green-cip.cn-shanghai.aliyuncs.com`,
              });
              return new Green20220302.default(config);
          }
      
          static async main() {
              const client = Client.createClient();
              // 构造请求对象
              const describeImageModerationResultRequest = new Green20220302.DescribeImageModerationResultRequest({
                  "reqId": "5B61EF1B-FF90-5264-8083-9FA75E955E01",
              });
              // 创建运行时配置对象
              const runtime = new Util.RuntimeOptions();
              try {
                  // 发起请求并获取响应
                  const response = await client.describeImageModerationResultWithOptions(describeImageModerationResultRequest, runtime);
                  console.log(JSON.stringify(response.body));
              } catch (error) {
                  // 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
                  // 错误 message
                  console.log('Error occurred:', error.message);
              }
          }
      }
      
      Client.main();
    • service同步接口接入示例

      const Green20220302 = require('@alicloud/green20220302');
      const OpenApi = require('@alicloud/openapi-client');
      const Util = require('@alicloud/tea-util');
      // 注意:此处实例化的client尽可能重复使用,提升检测性能。避免重复建立连接。
      // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
      class Client {
          static createClient() {
              const config = new OpenApi.Config({
                  // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                  // accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                  // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                  // accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                  endpoint: `green-cip.cn-shanghai.aliyuncs.com`,
              });
              return new Green20220302.default(config);
          }
      
          static async main() {
              const client = Client.createClient();
              // 构造请求对象
              const imageBatchModerationRequest = new Green20220302.ImageBatchModerationRequest({
                  "service": "baselineCheck,profilePhotoCheck",
                  "serviceParameters": JSON.stringify({
                  // 待检测文件所在bucket的区域。 示例:cn-shanghai
                  "ossRegionId": "cn-shanghai",
                  // 待检测文件所在bucket名称。示例:bucket001
                  "ossBucketName": "bucket001",
                  // 待检测文件。 示例:image/001.jpg
                  "ossObjectName": "image/001.jpg",
                  // 数据唯一标识
                  "dataId": uuidv4()
                  })
              });
              // 创建运行时配置对象
              const runtime = new Util.RuntimeOptions();
              try {
                  // 发起请求并获取响应
                  const response = await client.imageBatchModerationWithOptions(imageBatchModerationRequest, runtime);
                  console.log(JSON.stringify(response.body));
              } catch (error) {
                  // 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
                  // 错误 message
                  console.log('Error occurred:', error.message);
              }
          }
      }
      
      Client.main();

C# SDK

原始代码,请参见C# SDK源码

支持以下三种类型的图片检测。

对公网可访问图片进行检测

使用场景

当需要审核的图片可通过公网链接访问时,图片审核增强版服务可通过图片URL获取文件后进行审核。

  1. 安装C# SDK。

    dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.19.1
  2. 接入C# SDK。

    • 同步接口接入示例

      // This file is auto-generated, don't edit it. Thanks.
      
      using Newtonsoft.Json;
      
      namespace AlibabaCloud.SDK.Green20220302
      {
          public class ImageModerationAutoRoute
          {
              public static void Main(string[] args)
              {
                  /**
                  * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
                  * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
                  * 常见获取环境变量方式:
                  * 获取RAM用户AccessKey ID:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * 获取RAM用户AccessKey Secret:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  String accessKeyId = "建议从环境变量中获取RAM用户AccessKey ID";
                  String accessKeySecret = "建议从环境变量中获取RAM用户AccessKey Secret";
                  // 接入区域和地址请根据实际情况修改
                  String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  //注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
                  Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
                  // 运行时参数设置,仅对使用了该运行时参数实例的请求有效
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                      new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
      
                  //构建图片检测请求。
                  Models.ImageModerationRequest imageModerationRequest =
                      new Models.ImageModerationRequest();
                  //图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
                	//支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff  
                	imageModerationRequest.Service = "baselineCheck";
                  Dictionary<string, object> task = new Dictionary<string, object>();
                  //待检测图片链接,公网可访问的URL。
                  task.Add(
                      "imageUrl",
                      "https://img.alicdn.com/tfs/xxxxxxxxxx001.png"
                  );
                  //待检测数据的ID。
                  task.Add("dataId", Guid.NewGuid().ToString());
                  imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
      
                  try
                  {
                      //调用API获取检测结果。
                      Models.ImageModerationResponse response = client.ImageModerationWithOptions(
                          imageModerationRequest,
                          runtimeOptions
                      );
                      //自动路由,区域切换至cn-beijing。
                      if (
                          response is null
                          || response.Body is null
                          || AlibabaCloud.TeaUtil.Common.EqualNumber(
                              500,
                              AlibabaCloud.TeaUtil.Common.AssertAsNumber(response.StatusCode)
                          )
                          || AlibabaCloud.TeaUtil.Common.EqualString(
                              "500",
                              Convert.ToString(response.Body.Code)
                          )
                      )
                      {
                          endpoint = "green-cip.cn-beijing.aliyuncs.com";
                          client = createClient(accessKeyId, accessKeySecret, endpoint);
                          response = client.ImageModerationWithOptions(
                              imageModerationRequest,
                              runtimeOptions
                          );
                      }
      
                      Console.WriteLine(response.Body.RequestId);
                      Console.WriteLine(JsonConvert.SerializeObject(response.Body));
                  }
                  catch (Exception _err)
                  {
                      Console.WriteLine(_err);
                  }
              }
      
              //创建请求客户端
              public static Client createClient(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  AlibabaCloud.OpenApiClient.Models.Config config =
                      new AlibabaCloud.OpenApiClient.Models.Config
                      {
                          AccessKeyId = accessKeyId,
                          AccessKeySecret = accessKeySecret,
                          //设置HTTP代理。
                          //HttpProxy = "http://10.10.xx.xx:xxxx",
                          //设置HTTPS代理。
                          //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                          //访问的域名。
                          Endpoint = endpoint,
                      };
                  return new Client(config);
              }
          }
      }
    • 异步接口接入示例

      提交异步图片检测任务

      using System;
      using Newtonsoft.Json;
      using Aliyun.OSS;
      
      namespace AlibabaCloud.SDK.Green20220302
      {
          public class ImageAsyncModerationAutoRoute
          {
      
              public static void Main(string[] args)
              {
                  /**
                  * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
                  * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
                  * 常见获取环境变量方式:
                  * 获取RAM用户AccessKey ID:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * 获取RAM用户AccessKey Secret:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  String accessKeyId = "推荐从环境变量获取 accessKeyId";
                  String accessKeySecret = "推荐从环境变量获取 accessKeySecret";
                  // 接入区域和地址请根据实际情况修改
                  String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  Models.ImageAsyncModerationResponse response = invoke(
                      accessKeyId,
                      accessKeySecret,
                      endpoint
                  );
                  //自动路由,区域切换至cn-beijing
                  if (
                      response is null
                      || response.Body is null
                      || AlibabaCloud.TeaUtil.Common.EqualNumber(
                          500,
                          AlibabaCloud.TeaUtil.Common.AssertAsNumber(response.StatusCode)
                      )
                      || AlibabaCloud.TeaUtil.Common.EqualString(
                          "500",
                          Convert.ToString(response.Body.Code)
                      )
                  )
                  {
                      endpoint = "green-cip.cn-beijing.aliyuncs.com";
                      response = invoke(accessKeyId, accessKeySecret, endpoint);
                      ;
                  }
      
                  Console.WriteLine(response.Body.RequestId);
                  Console.WriteLine(JsonConvert.SerializeObject(response.Body));
              }
      
              //创建请求客户端
              public static Client createClient(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  AlibabaCloud.OpenApiClient.Models.Config config =
                      new AlibabaCloud.OpenApiClient.Models.Config
                      {
                          AccessKeyId = accessKeyId,
                          AccessKeySecret = accessKeySecret,
                          //设置HTTP代理。
                          //HttpProxy = "http://10.10.xx.xx:xxxx",
                          //设置HTTPS代理。
                          //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                          //访问的域名。
                          Endpoint = endpoint,
                      };
                  return new Client(config);
              }
      
      
              //提交检测请求
              public static Models.ImageAsyncModerationResponse invoke(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  //注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
                  Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
                  //运行时参数设置,仅对使用了该运行时参数实例的请求有效
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                      new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
      
                  try
                  {
      
                      //构建检测请求
                      Models.ImageAsyncModerationRequest imageAsyncModerationRequest =
                          new Models.ImageAsyncModerationRequest();
                      //检测service:示例:baselineCheck
                        imageAsyncModerationRequest.Service = "baselineCheck";
                      Dictionary<string, object> task = new Dictionary<string, object>();
                      //待检测信息
                      task.Add("imageUrl", "https://www.aliyun.com/a.jpg");
                      //待检测数据的ID
                      task.Add("dataId", Guid.NewGuid().ToString());
                      imageAsyncModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
                      //发起请求
                      Models.ImageAsyncModerationResponse response = client.ImageAsyncModerationWithOptions(
                          imageAsyncModerationRequest,
                          runtimeOptions
                      );
                      return response;
                  }
                  catch (Exception _err)
                  {
                      Console.WriteLine(_err);
                      return null;
                  }
              }
          }
      }

      获取异步图片检测结果

      using System;
      using Newtonsoft.Json;
      using Aliyun.OSS;
      
      namespace AlibabaCloud.SDK.Green20220302
      {
          public class DescribeImageModerationResultAutoRoute
          {
      
              public static void Main(string[] args)
              {
                  /**
                  * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
                  * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
                  * 常见获取环境变量方式:
                  * 获取RAM用户AccessKey ID:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * 获取RAM用户AccessKey Secret:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  String accessKeyId = "推荐从环境变量获取 accessKeyId";
                  String accessKeySecret = "推荐从环境变量获取 accessKeySecret";
                  // 接入区域和地址请根据实际情况修改
                  String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  Models.DescribeImageModerationResultResponse response = invoke(
                      accessKeyId,
                      accessKeySecret,
                      endpoint
                  );
      
                  Console.WriteLine(response.Body.RequestId);
                  Console.WriteLine(JsonConvert.SerializeObject(response.Body));
              }
      
              //创建请求客户端
              public static Client createClient(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  AlibabaCloud.OpenApiClient.Models.Config config =
                      new AlibabaCloud.OpenApiClient.Models.Config
                      {
                          AccessKeyId = accessKeyId,
                          AccessKeySecret = accessKeySecret,
                          //设置HTTP代理。
                          //HttpProxy = "http://10.10.xx.xx:xxxx",
                          //设置HTTPS代理。
                          //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                          //访问的域名。
                          Endpoint = endpoint,
                      };
                  return new Client(config);
              }
      
      
              //提交检测请求
              public static Models.DescribeImageModerationResultResponse invoke(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  //注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
                  Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
                  //运行时参数设置,仅对使用了该运行时参数实例的请求有效
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                      new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
      
                  try
                  {
      
                      //构建检测请求
                      Models.DescribeImageModerationResultRequest describeImageModerationResultRequest =
                          new Models.DescribeImageModerationResultRequest();
                        describeImageModerationResultRequest.ReqId = "ABCD1234-1234-1234-1234-123****";
                      //发起请求
                      Models.DescribeImageModerationResultResponse response = client.DescribeImageModerationResultWithOptions(
                          describeImageModerationResultRequest,
                          runtimeOptions
                      );
                      return response;
                  }
                  catch (Exception _err)
                  {
                      Console.WriteLine(_err);
                      return null;
                  }
              }
          }
      }
    • service同步接口接入示例

      // This file is auto-generated, don't edit it. Thanks.
      
      using Newtonsoft.Json;
      
      namespace AlibabaCloud.SDK.Green20220302
      {
          public class ImageBatchModerationAutoRoute
          {
              public static void Main(string[] args)
              {
                  /**
                  * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
                  * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
                  * 常见获取环境变量方式:
                  * 获取RAM用户AccessKey ID:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * 获取RAM用户AccessKey Secret:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  String accessKeyId = "建议从环境变量中获取RAM用户AccessKey ID";
                  String accessKeySecret = "建议从环境变量中获取RAM用户AccessKey Secret";
                  // 接入区域和地址请根据实际情况修改
                  String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  //注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
                  Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
                  // 运行时参数设置,仅对使用了该运行时参数实例的请求有效
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                      new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
      
                  //构建图片检测请求。
                  Models.ImageBatchModerationRequest imageBatchModerationRequest =
                      new Models.ImageBatchModerationRequest();
                  //图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck 
                    imageBatchModerationRequest.Service = "baselineCheck,profilePhotoCheck";
                  Dictionary<string, object> task = new Dictionary<string, object>();
                  //待检测图片链接,公网可访问的URL。
                  task.Add(
                      "imageUrl",
                      "https://img.alicdn.com/tfs/xxxxxxxxxx001.png"
                  );
                  //待检测数据的ID。
                  task.Add("dataId", Guid.NewGuid().ToString());
                  imageBatchModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
      
                  try
                  {
                      //调用API获取检测结果。
                      Models.ImageBatchModerationResponse response = client.ImageBatchModerationWithOptions(
                          imageBatchModerationRequest,
                          runtimeOptions
                      );
                      //自动路由,区域切换至cn-beijing。
                      if (
                          response is null
                          || response.Body is null
                          || AlibabaCloud.TeaUtil.Common.EqualNumber(
                              500,
                              AlibabaCloud.TeaUtil.Common.AssertAsNumber(response.StatusCode)
                          )
                          || AlibabaCloud.TeaUtil.Common.EqualString(
                              "500",
                              Convert.ToString(response.Body.Code)
                          )
                      )
                      {
                          endpoint = "green-cip.cn-beijing.aliyuncs.com";
                          client = createClient(accessKeyId, accessKeySecret, endpoint);
                          response = client.ImageBatchModerationWithOptions(
                              imageBatchModerationRequest,
                              runtimeOptions
                          );
                      }
      
                      Console.WriteLine(response.Body.RequestId);
                      Console.WriteLine(JsonConvert.SerializeObject(response.Body));
                  }
                  catch (Exception _err)
                  {
                      Console.WriteLine(_err);
                  }
              }
      
              //创建请求客户端
              public static Client createClient(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  AlibabaCloud.OpenApiClient.Models.Config config =
                      new AlibabaCloud.OpenApiClient.Models.Config
                      {
                          AccessKeyId = accessKeyId,
                          AccessKeySecret = accessKeySecret,
                          //设置HTTP代理。
                          //HttpProxy = "http://10.10.xx.xx:xxxx",
                          //设置HTTPS代理。
                          //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                          //访问的域名。
                          Endpoint = endpoint,
                      };
                  return new Client(config);
              }
          }
      }

对本地图片进行检测

使用场景

当您需要审核的图片在本地机器且无公网访问链接,您可以将图片上传到内容安全提供的对象存储OSS Bucket中,图片审核增强版服务可直接访问对象存储OSS,获取到图片内容后进行审核。

  1. 安装C# SDK。

    安装内容安全SDK:

    dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.19.1

    安装OSS SDK:

    //。
    dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.8
    //。
    NuGet方式安装 
    1.如果您的Visual Studio没有安装NuGet,请先安装NuGet。
    2.在Visual Studio中新建或者打开已有的项目,选择工具 > NuGet程序包管理器 > 管理解决方案的NuGet程序包。
    3.搜索aliyun.oss.sdk,在结果中找到Aliyun.OSS.SDK(适用于.NET Framework)或Aliyun.OSS.SDK.NetCore(适用于.Net Core),选择最新版本,单击安装。
  2. 接入C# SDK。

    • 同步接口接入示例

      // This file is auto-generated, don't edit it. Thanks.
      
      using System;
      using Newtonsoft.Json;
      using Aliyun.OSS;
      
      namespace AlibabaCloud.SDK.Green20220302
      {
          public class ImageModerationAutoRoute
          {
              //文件上传token
              public static Dictionary<String, Models.DescribeUploadTokenResponse> tokenDic =
                  new Dictionary<String, Models.DescribeUploadTokenResponse>();
      
              //文件上传客户端
              public static OssClient ossClient = null;
      
              //服务是否部署在VPC上
              public static Boolean isVPC = false;
      
              public static void Main(string[] args)
              {
                  /**
                  * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
                  * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
                  * 常见获取环境变量方式:
                  * 获取RAM用户AccessKey ID:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * 获取RAM用户AccessKey Secret:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  String accessKeyId = "建议从环境变量中获取RAM用户AccessKey ID";
                  String accessKeySecret = "建议从环境变量中获取RAM用户AccessKey Secret";
                  // 接入区域和地址请根据实际情况修改
                  String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  Models.ImageModerationResponse response = invoke(
                      accessKeyId,
                      accessKeySecret,
                      endpoint
                  );
                  //自动路由,区域切换至cn-beijing
                  if (
                      response is null
                      || response.Body is null
                      || AlibabaCloud.TeaUtil.Common.EqualNumber(
                          500,
                          AlibabaCloud.TeaUtil.Common.AssertAsNumber(response.StatusCode)
                      )
                      || AlibabaCloud.TeaUtil.Common.EqualString(
                          "500",
                          Convert.ToString(response.Body.Code)
                      )
                  )
                  {
                      endpoint = "green-cip.cn-beijing.aliyuncs.com";
                      response = invoke(accessKeyId, accessKeySecret, endpoint);
                      ;
                  }
      
                  Console.WriteLine(response.Body.RequestId);
                  Console.WriteLine(JsonConvert.SerializeObject(response.Body));
              }
      
              //创建请求客户端
              public static Client createClient(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  AlibabaCloud.OpenApiClient.Models.Config config =
                      new AlibabaCloud.OpenApiClient.Models.Config
                      {
                          AccessKeyId = accessKeyId,
                          AccessKeySecret = accessKeySecret,
                          //设置HTTP代理。
                          //HttpProxy = "http://10.10.xx.xx:xxxx",
                          //设置HTTPS代理。
                          //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                          //访问的域名。
                          Endpoint = endpoint,
                      };
                  return new Client(config);
              }
      
              //创建文件上传客户端
              private static OssClient getOssClient(
                  Models.DescribeUploadTokenResponse tokenResponse,
                  Boolean isVPC
              )
              {
                  var tokenData = tokenResponse.Body.Data;
                  if (isVPC)
                  {
                      return new OssClient(
                          tokenData.OssInternalEndPoint,
                          tokenData.AccessKeyId,
                          tokenData.AccessKeySecret,
                          tokenData.SecurityToken
                      );
                  }
                  else
                  {
                      return new OssClient(
                          tokenData.OssInternetEndPoint,
                          tokenData.AccessKeyId,
                          tokenData.AccessKeySecret,
                          tokenData.SecurityToken
                      );
                  }
              }
      
              //上传文件
              public static String uploadFile(
                  String filePath,
                  Models.DescribeUploadTokenResponse tokenResponse
              )
              {
                  // 构造OssClient实例。
                  ossClient = getOssClient(tokenResponse, isVPC);
                  var tokenData = tokenResponse.Body.Data;
      
                  String objectName =
                      tokenData.FileNamePrefix
                      + Guid.NewGuid().ToString()
                      + "."
                      + filePath.Split(".").GetValue(1);
                  //上传文件
                  ossClient.PutObject(tokenData.BucketName, objectName, filePath);
                  return objectName;
              }
      
              //提交检测请求
              public static Models.ImageModerationResponse invoke(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  //注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
                  Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
                  //运行时参数设置,仅对使用了该运行时参数实例的请求有效
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                      new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
      
                  //本地文件的完整路径,例如D:\localPath\exampleFile.png。
                  String filePath = "D:\localPath\exampleFile.png";
                  try
                  {
                      //获取文件上传临时token
                      if (
                          !tokenDic.ContainsKey(endpoint)
                          || tokenDic[endpoint].Body.Data.Expiration
                              <= DateTimeOffset.Now.ToUnixTimeSeconds()
                      )
                      {
                          var tokenResponse = client.DescribeUploadToken();
                          tokenDic[endpoint] = tokenResponse;
                      }
                      //上传文件
                      String objectName = uploadFile(filePath, tokenDic[endpoint]);
                      //构建图片检测请求
                      Models.ImageModerationRequest imageModerationRequest =
                          new Models.ImageModerationRequest();
                      //图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
                      //支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
                    	imageModerationRequest.Service = "baselineCheck";
                      Dictionary<string, object> task = new Dictionary<string, object>();
                      //待检测图片信息
                      task.Add("ossBucketName", tokenDic[endpoint].Body.Data.BucketName);
                      task.Add("ossObjectName", objectName);
                      //待检测数据的ID
                      task.Add("dataId", Guid.NewGuid().ToString());
                      imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
                      //调用API获取检测结果
                      Models.ImageModerationResponse response = client.ImageModerationWithOptions(
                          imageModerationRequest,
                          runtimeOptions
                      );
                      return response;
                  }
                  catch (Exception _err)
                  {
                      Console.WriteLine(_err);
                      return null;
                  }
              }
          }
      }
    • 异步接口接入示例

      提交异步图片检测任务

      // This file is auto-generated, don't edit it. Thanks.
      
      using System;
      using Newtonsoft.Json;
      using Aliyun.OSS;
      
      namespace AlibabaCloud.SDK.Green20220302
      {
          public class ImageAsyncModerationAutoRoute
          {
              //文件上传token
              public static Dictionary<String, Models.DescribeUploadTokenResponse> tokenDic =
                  new Dictionary<String, Models.DescribeUploadTokenResponse>();
      
              //文件上传客户端
              public static OssClient ossClient = null;
      
              //服务是否部署在VPC上
              public static Boolean isVPC = false;
      
              public static void Main(string[] args)
              {
                  /**
                  * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
                  * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
                  * 常见获取环境变量方式:
                  * 获取RAM用户AccessKey ID:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * 获取RAM用户AccessKey Secret:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  String accessKeyId = "建议从环境变量中获取RAM用户AccessKey ID";
                  String accessKeySecret = "建议从环境变量中获取RAM用户AccessKey Secret";
                  // 接入区域和地址请根据实际情况修改
                  String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  Models.ImageAsyncModerationResponse response = invoke(
                      accessKeyId,
                      accessKeySecret,
                      endpoint
                  );
                  //自动路由,区域切换至cn-beijing
                  if (
                      response is null
                      || response.Body is null
                      || AlibabaCloud.TeaUtil.Common.EqualNumber(
                          500,
                          AlibabaCloud.TeaUtil.Common.AssertAsNumber(response.StatusCode)
                      )
                      || AlibabaCloud.TeaUtil.Common.EqualString(
                          "500",
                          Convert.ToString(response.Body.Code)
                      )
                  )
                  {
                      endpoint = "green-cip.cn-beijing.aliyuncs.com";
                      response = invoke(accessKeyId, accessKeySecret, endpoint);
                      ;
                  }
      
                  Console.WriteLine(response.Body.RequestId);
                  Console.WriteLine(JsonConvert.SerializeObject(response.Body));
              }
      
              //创建请求客户端
              public static Client createClient(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  AlibabaCloud.OpenApiClient.Models.Config config =
                      new AlibabaCloud.OpenApiClient.Models.Config
                      {
                          AccessKeyId = accessKeyId,
                          AccessKeySecret = accessKeySecret,
                          //设置HTTP代理。
                          //HttpProxy = "http://10.10.xx.xx:xxxx",
                          //设置HTTPS代理。
                          //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                          //访问的域名。
                          Endpoint = endpoint,
                      };
                  return new Client(config);
              }
      
              //创建文件上传客户端
              private static OssClient getOssClient(
                  Models.DescribeUploadTokenResponse tokenResponse,
                  Boolean isVPC
              )
              {
                  var tokenData = tokenResponse.Body.Data;
                  if (isVPC)
                  {
                      return new OssClient(
                          tokenData.OssInternalEndPoint,
                          tokenData.AccessKeyId,
                          tokenData.AccessKeySecret,
                          tokenData.SecurityToken
                      );
                  }
                  else
                  {
                      return new OssClient(
                          tokenData.OssInternetEndPoint,
                          tokenData.AccessKeyId,
                          tokenData.AccessKeySecret,
                          tokenData.SecurityToken
                      );
                  }
              }
      
              //上传文件
              public static String uploadFile(
                  String filePath,
                  Models.DescribeUploadTokenResponse tokenResponse
              )
              {
                  // 构造OssClient实例。
                  ossClient = getOssClient(tokenResponse, isVPC);
                  var tokenData = tokenResponse.Body.Data;
      
                  String objectName =
                      tokenData.FileNamePrefix
                      + Guid.NewGuid().ToString()
                      + "."
                      + filePath.Split(".").GetValue(1);
                  //上传文件
                  ossClient.PutObject(tokenData.BucketName, objectName, filePath);
                  return objectName;
              }
      
              //提交检测请求
              public static Models.ImageAsyncModerationResponse invoke(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  //注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
                  Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
                  //运行时参数设置,仅对使用了该运行时参数实例的请求有效
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                      new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
      
                  //本地文件的完整路径,例如D:\localPath\exampleFile.jpg。
                  String filePath = "/Users/admin/test/image/1.jpg";
                  try
                  {
                      //获取文件上传临时token
                      if (
                          !tokenDic.ContainsKey(endpoint)
                          || tokenDic[endpoint].Body.Data.Expiration
                              <= DateTimeOffset.Now.ToUnixTimeSeconds()
                      )
                      {
                          var tokenResponse = client.DescribeUploadToken();
                          tokenDic[endpoint] = tokenResponse;
                      }
                      //上传文件
                      String objectName = uploadFile(filePath, tokenDic[endpoint]);
                      //构建检测请求
                      Models.ImageAsyncModerationRequest imageAsyncModerationRequest =
                          new Models.ImageAsyncModerationRequest();
                      //检测service:示例:baselineCheck
                        imageAsyncModerationRequest.Service = "baselineCheck";
                      Dictionary<string, object> task = new Dictionary<string, object>();
                      //待检测信息
                      task.Add("ossBucketName", tokenDic[endpoint].Body.Data.BucketName);
                      task.Add("ossObjectName", objectName);
                      //待检测数据的ID
                      task.Add("dataId", Guid.NewGuid().ToString());
                      imageAsyncModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
                      //发起请求
                      Models.ImageAsyncModerationResponse response = client.ImageAsyncModerationWithOptions(
                          imageAsyncModerationRequest,
                          runtimeOptions
                      );
                      return response;
                  }
                  catch (Exception _err)
                  {
                      Console.WriteLine(_err);
                      return null;
                  }
              }
          }
      }

      获取异步图片检测结果

      using System;
      using Newtonsoft.Json;
      using Aliyun.OSS;
      
      namespace AlibabaCloud.SDK.Green20220302
      {
          public class DescribeImageModerationResultAutoRoute
          {
      
              public static void Main(string[] args)
              {
                  /**
                  * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
                  * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
                  * 常见获取环境变量方式:
                  * 获取RAM用户AccessKey ID:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * 获取RAM用户AccessKey Secret:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  String accessKeyId = "推荐从环境变量获取 accessKeyId";
                  String accessKeySecret = "推荐从环境变量获取 accessKeySecret";
                  // 接入区域和地址请根据实际情况修改
                  String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  Models.DescribeImageModerationResultResponse response = invoke(
                      accessKeyId,
                      accessKeySecret,
                      endpoint
                  );
      
                  Console.WriteLine(response.Body.RequestId);
                  Console.WriteLine(JsonConvert.SerializeObject(response.Body));
              }
      
              //创建请求客户端
              public static Client createClient(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  AlibabaCloud.OpenApiClient.Models.Config config =
                      new AlibabaCloud.OpenApiClient.Models.Config
                      {
                          AccessKeyId = accessKeyId,
                          AccessKeySecret = accessKeySecret,
                          //设置HTTP代理。
                          //HttpProxy = "http://10.10.xx.xx:xxxx",
                          //设置HTTPS代理。
                          //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                          //访问的域名。
                          Endpoint = endpoint,
                      };
                  return new Client(config);
              }
      
      
              //提交检测请求
              public static Models.DescribeImageModerationResultResponse invoke(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  //注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
                  Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
                  //运行时参数设置,仅对使用了该运行时参数实例的请求有效
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                      new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
      
                  try
                  {
      
                      //构建检测请求
                      Models.DescribeImageModerationResultRequest describeImageModerationResultRequest =
                          new Models.DescribeImageModerationResultRequest();
                        describeImageModerationResultRequest.ReqId = "ABCD1234-1234-1234-1234-123****";
                      //发起请求
                      Models.DescribeImageModerationResultResponse response = client.DescribeImageModerationResultWithOptions(
                          describeImageModerationResultRequest,
                          runtimeOptions
                      );
                      return response;
                  }
                  catch (Exception _err)
                  {
                      Console.WriteLine(_err);
                      return null;
                  }
              }
          }
      }
    • service同步接口接入示例

      // This file is auto-generated, don't edit it. Thanks.
      
      using System;
      using Newtonsoft.Json;
      using Aliyun.OSS;
      
      namespace AlibabaCloud.SDK.Green20220302
      {
          public class ImageBatchModerationAutoRoute
          {
              //文件上传token
              public static Dictionary<String, Models.DescribeUploadTokenResponse> tokenDic =
                  new Dictionary<String, Models.DescribeUploadTokenResponse>();
      
              //文件上传客户端
              public static OssClient ossClient = null;
      
              //服务是否部署在VPC上
              public static Boolean isVPC = false;
      
              public static void Main(string[] args)
              {
                  /**
                  * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
                  * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
                  * 常见获取环境变量方式:
                  * 获取RAM用户AccessKey ID:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * 获取RAM用户AccessKey Secret:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  String accessKeyId = "建议从环境变量中获取RAM用户AccessKey ID";
                  String accessKeySecret = "建议从环境变量中获取RAM用户AccessKey Secret";
                  // 接入区域和地址请根据实际情况修改
                  String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  Models.ImageBatchModerationResponse response = invoke(
                      accessKeyId,
                      accessKeySecret,
                      endpoint
                  );
                  //自动路由,区域切换至cn-beijing
                  if (
                      response is null
                      || response.Body is null
                      || AlibabaCloud.TeaUtil.Common.EqualNumber(
                          500,
                          AlibabaCloud.TeaUtil.Common.AssertAsNumber(response.StatusCode)
                      )
                      || AlibabaCloud.TeaUtil.Common.EqualString(
                          "500",
                          Convert.ToString(response.Body.Code)
                      )
                  )
                  {
                      endpoint = "green-cip.cn-beijing.aliyuncs.com";
                      response = invoke(accessKeyId, accessKeySecret, endpoint);
                      ;
                  }
      
                  Console.WriteLine(response.Body.RequestId);
                  Console.WriteLine(JsonConvert.SerializeObject(response.Body));
              }
      
              //创建请求客户端
              public static Client createClient(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  AlibabaCloud.OpenApiClient.Models.Config config =
                      new AlibabaCloud.OpenApiClient.Models.Config
                      {
                          AccessKeyId = accessKeyId,
                          AccessKeySecret = accessKeySecret,
                          //设置HTTP代理。
                          //HttpProxy = "http://10.10.xx.xx:xxxx",
                          //设置HTTPS代理。
                          //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                          //访问的域名。
                          Endpoint = endpoint,
                      };
                  return new Client(config);
              }
      
              //创建文件上传客户端
              private static OssClient getOssClient(
                  Models.DescribeUploadTokenResponse tokenResponse,
                  Boolean isVPC
              )
              {
                  var tokenData = tokenResponse.Body.Data;
                  if (isVPC)
                  {
                      return new OssClient(
                          tokenData.OssInternalEndPoint,
                          tokenData.AccessKeyId,
                          tokenData.AccessKeySecret,
                          tokenData.SecurityToken
                      );
                  }
                  else
                  {
                      return new OssClient(
                          tokenData.OssInternetEndPoint,
                          tokenData.AccessKeyId,
                          tokenData.AccessKeySecret,
                          tokenData.SecurityToken
                      );
                  }
              }
      
              //上传文件
              public static String uploadFile(
                  String filePath,
                  Models.DescribeUploadTokenResponse tokenResponse
              )
              {
                  // 构造OssClient实例。
                  ossClient = getOssClient(tokenResponse, isVPC);
                  var tokenData = tokenResponse.Body.Data;
      
                  String objectName =
                      tokenData.FileNamePrefix
                      + Guid.NewGuid().ToString()
                      + "."
                      + filePath.Split(".").GetValue(1);
                  //上传文件
                  ossClient.PutObject(tokenData.BucketName, objectName, filePath);
                  return objectName;
              }
      
              //提交检测请求
              public static Models.ImageBatchModerationResponse invoke(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  //注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
                  Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
                  //运行时参数设置,仅对使用了该运行时参数实例的请求有效
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                      new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
      
                  //本地文件的完整路径,例如D:\localPath\exampleFile.png。
                  String filePath = "D:\localPath\exampleFile.png";
                  try
                  {
                      //获取文件上传临时token
                      if (
                          !tokenDic.ContainsKey(endpoint)
                          || tokenDic[endpoint].Body.Data.Expiration
                              <= DateTimeOffset.Now.ToUnixTimeSeconds()
                      )
                      {
                          var tokenResponse = client.DescribeUploadToken();
                          tokenDic[endpoint] = tokenResponse;
                      }
                      //上传文件
                      String objectName = uploadFile(filePath, tokenDic[endpoint]);
                      //构建图片检测请求
                      Models.ImageBatchModerationRequest imageBatchModerationRequest =
                          new Models.ImageBatchModerationRequest();
                      //图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
                        imageBatchModerationRequest.Service = "baselineCheck,profilePhotoCheck";
                      Dictionary<string, object> task = new Dictionary<string, object>();
                      //待检测图片信息
                      task.Add("ossBucketName", tokenDic[endpoint].Body.Data.BucketName);
                      task.Add("ossObjectName", objectName);
                      //待检测数据的ID
                      task.Add("dataId", Guid.NewGuid().ToString());
                      imageBatchModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
                      //调用API获取检测结果
                      Models.ImageBatchModerationResponse response = client.ImageBatchModerationWithOptions(
                          imageBatchModerationRequest,
                          runtimeOptions
                      );
                      return response;
                  }
                  catch (Exception _err)
                  {
                      Console.WriteLine(_err);
                      return null;
                  }
              }
          }
      }

OSS图片进行检测

使用场景

如果您需要审核的图片文件已经存储在阿里云对象存储OSS中,你可授权创建服务角色,允许内容安全服务访问对象存储OSS。图片审核增强版服务会通过服务角色获取到对象存储OSS的文件后进行审核。访问云资源访问授权页面创建服务角色。

  1. 使用阿里云账号(即主账号)访问云资源访问授权页面进行授权。

  2. 安装C# SDK。

    dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.19.1
  3. 接入C# SDK。

    • 同步接口接入示例

      // This file is auto-generated, don't edit it. Thanks.
      
      using Newtonsoft.Json;
      
      namespace AlibabaCloud.SDK.Green20220302
      {
          public class OssScanDemo
          {
              public static void Main(string[] args)
              {
                  /**
                  * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
                  * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
                  * 常见获取环境变量方式:
                  * 获取RAM用户AccessKey ID:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * 获取RAM用户AccessKey Secret:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  String accessKeyId = "建议从环境变量中获取RAM用户AccessKey ID";
                  String accessKeySecret = "建议从环境变量中获取RAM用户AccessKey Secret";
                  // 接入区域和地址请根据实际情况修改
                  String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  //注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
                  Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
                  // 运行时参数设置,仅对使用了该运行时参数实例的请求有效
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                      new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
      
                  //构建图片检测请求。
                  Models.ImageModerationRequest imageModerationRequest =
                      new Models.ImageModerationRequest();
                  //图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
                  //支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
                	imageModerationRequest.Service = "baselineCheck";
                  Dictionary<string, object> task = new Dictionary<string, object>();
                  //待检测图片的OSSbucket所在region。示例:cn-shanghai
                  task.Add("ossRegionId", "cn-shanghai");
                  //待检测图片的OSSbucket名称。示例:bucket001
                  task.Add("ossBucketName", "bucket001");
                  //待检测图片的Object名称。示例:image/001.jpg
                  task.Add("ossObjectName", "image/001.jpg");
                  //待检测数据的ID。
                  task.Add("dataId", Guid.NewGuid().ToString());
                  imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
                  try
                  {
                      //调用API获取检测结果。
                      Models.ImageModerationResponse response = client.ImageModerationWithOptions(
                          imageModerationRequest,
                          runtimeOptions
                      );
                      //自动路由,区域切换至cn-beijing。
                      if (
                          response is null
                          || response.Body is null
                          || AlibabaCloud.TeaUtil.Common.EqualNumber(
                              500,
                              AlibabaCloud.TeaUtil.Common.AssertAsNumber(response.StatusCode)
                          )
                          || AlibabaCloud.TeaUtil.Common.EqualString(
                              "500",
                              Convert.ToString(response.Body.Code)
                          )
                      )
                      {
                          endpoint = "green-cip.cn-beijing.aliyuncs.com";
                          client = createClient(accessKeyId, accessKeySecret, endpoint);
                          response = client.ImageModerationWithOptions(
                              imageModerationRequest,
                              runtimeOptions
                          );
                      }
      
                      Console.WriteLine(response.Body.RequestId);
                      Console.WriteLine(JsonConvert.SerializeObject(response.Body));
                  }
                  catch (Exception _err)
                  {
                      Console.WriteLine(_err);
                  }
              }
      
              //创建请求客户端
              public static Client createClient(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  AlibabaCloud.OpenApiClient.Models.Config config =
                      new AlibabaCloud.OpenApiClient.Models.Config
                      {
                          AccessKeyId = accessKeyId,
                          AccessKeySecret = accessKeySecret,
                          //设置HTTP代理。
                          //HttpProxy = "http://10.10.xx.xx:xxxx",
                          //设置HTTPS代理。
                          //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                          //访问的域名。
                          Endpoint = endpoint,
                      };
                  return new Client(config);
              }
          }
      }
    • 异步接口接入示例

      提交异步图片检测任务

      using System;
      using Newtonsoft.Json;
      using Aliyun.OSS;
      
      namespace AlibabaCloud.SDK.Green20220302
      {
          public class ImageAsyncModerationAutoRoute
          {
      
              public static void Main(string[] args)
              {
                  /**
                  * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
                  * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
                  * 常见获取环境变量方式:
                  * 获取RAM用户AccessKey ID:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * 获取RAM用户AccessKey Secret:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  String accessKeyId = "推荐从环境变量获取 accessKeyId";
                  String accessKeySecret = "推荐从环境变量获取 accessKeySecret";
                  // 接入区域和地址请根据实际情况修改
                  String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  Models.ImageAsyncModerationResponse response = invoke(
                      accessKeyId,
                      accessKeySecret,
                      endpoint
                  );
                  //自动路由,区域切换至cn-beijing
                  if (
                      response is null
                      || response.Body is null
                      || AlibabaCloud.TeaUtil.Common.EqualNumber(
                          500,
                          AlibabaCloud.TeaUtil.Common.AssertAsNumber(response.StatusCode)
                      )
                      || AlibabaCloud.TeaUtil.Common.EqualString(
                          "500",
                          Convert.ToString(response.Body.Code)
                      )
                  )
                  {
                      endpoint = "green-cip.cn-beijing.aliyuncs.com";
                      response = invoke(accessKeyId, accessKeySecret, endpoint);
                      ;
                  }
      
                  Console.WriteLine(response.Body.RequestId);
                  Console.WriteLine(JsonConvert.SerializeObject(response.Body));
              }
      
              //创建请求客户端
              public static Client createClient(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  AlibabaCloud.OpenApiClient.Models.Config config =
                      new AlibabaCloud.OpenApiClient.Models.Config
                      {
                          AccessKeyId = accessKeyId,
                          AccessKeySecret = accessKeySecret,
                          //设置HTTP代理。
                          //HttpProxy = "http://10.10.xx.xx:xxxx",
                          //设置HTTPS代理。
                          //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                          //访问的域名。
                          Endpoint = endpoint,
                      };
                  return new Client(config);
              }
      
      
              //提交检测请求
              public static Models.ImageAsyncModerationResponse invoke(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  //注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
                  Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
                  //运行时参数设置,仅对使用了该运行时参数实例的请求有效
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                      new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
      
                  try
                  {
      
                      //构建检测请求
                      Models.ImageAsyncModerationRequest imageAsyncModerationRequest =
                          new Models.ImageAsyncModerationRequest();
                      //检测service:示例:baselineCheck
                        imageAsyncModerationRequest.Service = "baselineCheck";
                      Dictionary<string, object> task = new Dictionary<string, object>();
                      //待检测信息
                      task.Add("ossBucketName", "bucket1");
                      task.Add("ossObjectName", "aliyuntest.jpg");
                      task.Add("ossRegionId", "cn-shanghai");
                      //待检测数据的ID
                      task.Add("dataId", Guid.NewGuid().ToString());
                      imageAsyncModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
                      //发起请求
                      Models.ImageAsyncModerationResponse response = client.ImageAsyncModerationWithOptions(
                          imageAsyncModerationRequest,
                          runtimeOptions
                      );
                      return response;
                  }
                  catch (Exception _err)
                  {
                      Console.WriteLine(_err);
                      return null;
                  }
              }
          }
      }

      获取异步图片检测结果

      using System;
      using Newtonsoft.Json;
      using Aliyun.OSS;
      
      namespace AlibabaCloud.SDK.Green20220302
      {
          public class DescribeImageModerationResultAutoRoute
          {
      
              public static void Main(string[] args)
              {
                  /**
                  * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
                  * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
                  * 常见获取环境变量方式:
                  * 获取RAM用户AccessKey ID:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * 获取RAM用户AccessKey Secret:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  String accessKeyId = "推荐从环境变量获取 accessKeyId";
                  String accessKeySecret = "推荐从环境变量获取 accessKeySecret";
                  // 接入区域和地址请根据实际情况修改
                  String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  Models.DescribeImageModerationResultResponse response = invoke(
                      accessKeyId,
                      accessKeySecret,
                      endpoint
                  );
      
                  Console.WriteLine(response.Body.RequestId);
                  Console.WriteLine(JsonConvert.SerializeObject(response.Body));
              }
      
              //创建请求客户端
              public static Client createClient(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  AlibabaCloud.OpenApiClient.Models.Config config =
                      new AlibabaCloud.OpenApiClient.Models.Config
                      {
                          AccessKeyId = accessKeyId,
                          AccessKeySecret = accessKeySecret,
                          //设置HTTP代理。
                          //HttpProxy = "http://10.10.xx.xx:xxxx",
                          //设置HTTPS代理。
                          //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                          //访问的域名。
                          Endpoint = endpoint,
                      };
                  return new Client(config);
              }
      
      
              //提交检测请求
              public static Models.DescribeImageModerationResultResponse invoke(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  //注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
                  Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
                  //运行时参数设置,仅对使用了该运行时参数实例的请求有效
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                      new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
      
                  try
                  {
      
                      //构建检测请求
                      Models.DescribeImageModerationResultRequest describeImageModerationResultRequest =
                          new Models.DescribeImageModerationResultRequest();
                        describeImageModerationResultRequest.ReqId = "ABCD1234-1234-1234-1234-123****";
                      //发起请求
                      Models.DescribeImageModerationResultResponse response = client.DescribeImageModerationResultWithOptions(
                          describeImageModerationResultRequest,
                          runtimeOptions
                      );
                      return response;
                  }
                  catch (Exception _err)
                  {
                      Console.WriteLine(_err);
                      return null;
                  }
              }
          }
      }
    • service同步接口接入示例

      // This file is auto-generated, don't edit it. Thanks.
      
      using Newtonsoft.Json;
      
      namespace AlibabaCloud.SDK.Green20220302
      {
          public class OssScanDemo
          {
              public static void Main(string[] args)
              {
                  /**
                  * 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
                  * 强烈建议不要把AccessKey IDAccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
                  * 常见获取环境变量方式:
                  * 获取RAM用户AccessKey ID:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * 获取RAM用户AccessKey Secret:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  String accessKeyId = "建议从环境变量中获取RAM用户AccessKey ID";
                  String accessKeySecret = "建议从环境变量中获取RAM用户AccessKey Secret";
                  // 接入区域和地址请根据实际情况修改
                  String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  //注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
                  Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
                  // 运行时参数设置,仅对使用了该运行时参数实例的请求有效
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                      new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
      
                  //构建图片检测请求。
                  Models.ImageBatchModerationRequest imageBatchModerationRequest =
                      new Models.ImageBatchModerationRequest();
                  //图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
                    imageBatchModerationRequest.Service = "baselineCheck,profilePhotoCheck";
                  Dictionary<string, object> task = new Dictionary<string, object>();
                  //待检测图片的OSSbucket所在region。示例:cn-shanghai
                  task.Add("ossRegionId", "cn-shanghai");
                  //待检测图片的OSSbucket名称。示例:bucket001
                  task.Add("ossBucketName", "bucket001");
                  //待检测图片的Object名称。示例:image/001.jpg
                  task.Add("ossObjectName", "image/001.jpg");
                  //待检测数据的ID。
                  task.Add("dataId", Guid.NewGuid().ToString());
                  imageBatchModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
                  try
                  {
                      //调用API获取检测结果。
                      Models.ImageBatchModerationResponse response = client.ImageBatchModerationWithOptions(
                          imageBatchModerationRequest,
                          runtimeOptions
                      );
                      //自动路由,区域切换至cn-beijing。
                      if (
                          response is null
                          || response.Body is null
                          || AlibabaCloud.TeaUtil.Common.EqualNumber(
                              500,
                              AlibabaCloud.TeaUtil.Common.AssertAsNumber(response.StatusCode)
                          )
                          || AlibabaCloud.TeaUtil.Common.EqualString(
                              "500",
                              Convert.ToString(response.Body.Code)
                          )
                      )
                      {
                          endpoint = "green-cip.cn-beijing.aliyuncs.com";
                          client = createClient(accessKeyId, accessKeySecret, endpoint);
                          response = client.ImageBatchModerationWithOptions(
                              imageBatchModerationRequest,
                              runtimeOptions
                          );
                      }
      
                      Console.WriteLine(response.Body.RequestId);
                      Console.WriteLine(JsonConvert.SerializeObject(response.Body));
                  }
                  catch (Exception _err)
                  {
                      Console.WriteLine(_err);
                  }
              }
      
              //创建请求客户端
              public static Client createClient(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  AlibabaCloud.OpenApiClient.Models.Config config =
                      new AlibabaCloud.OpenApiClient.Models.Config
                      {
                          AccessKeyId = accessKeyId,
                          AccessKeySecret = accessKeySecret,
                          //设置HTTP代理。
                          //HttpProxy = "http://10.10.xx.xx:xxxx",
                          //设置HTTPS代理。
                          //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                          //访问的域名。
                          Endpoint = endpoint,
                      };
                  return new Client(config);
              }
          }
      }

HTTPS原生调用

内容安全增强版API服务也支持HTTPS原生调用,原生方式需要用户自行封装加解签、拼装请求(URL、Body、header、parameters)。通常必须使用HTTPS原生方式调用的仅有两种情形,如非下述两种特殊场景,建议使用SDK方式调用。

  1. 直接在App中使用,对客户端大小有高要求。

  2. 对个别的依赖lib包有指定,不方便升级。

  • 调用方式

    服务请求地址:https://green-cip.{region}.aliyuncs.com

    协议:HTTPS

    方式:POST

  • 公共请求参数

    图片审核增强版API接口的入参包含公共请求参数和具体接口请求参数,公共请求参数是指每一个接口都需要使用到的参数,以下表格是公共请求参数的详细介绍。

    名称

    类型

    是否必须

    描述

    Format

    String

    返回消息的格式。取值:

    • JSON (默认值)

    • XML

    Version

    String

    API版本号,使用YYYY-MM-DD日期格式,本版本对应为2022-03-02。

    AccessKeyId

    String

    阿里云颁发给用户的访问服务所用的密钥ID。

    Signature

    String

    签名结果串,关于签名的计算方法,请参见下方签名方式。

    SignatureMethod

    String

    签名方式,目前支持HMAC-SHA1。

    Timestamp

    String

    请求的时间戳。日期格式按照ISO8601标准表示,并需要使用UTC时间。格式为:yyyy-MM-ddTHH:mm:ssZ。例如,北京时间20221212091314秒表示为2022-12-12T01:13:14Z。

    SignatureVersion

    String

    签名算法版本,取值为1.0。

    SignatureNonce

    String

    唯一随机数,用于防止网络重放攻击。不同请求要使用不同的随机数值。

    Action

    String

    • 图片同步接口:ImageModeration

    • 图片异步接口:ImageAsyncModeration

    • 获取图片异步审核结果接口:DescribeImageModerationResult

    • 图片多service同步接口:ImageBatchModeration

  • 公共返回参数

    您发送的每次接口调用请求,无论成功与否,系统都会返回唯一识别码RequestId。其他返回参数包含label(标签)、confidence(置信分值),服务不同返回的参数不同,详见具体服务对应的文档。

  • 代码示例

    以下返回示例为了便于阅读,做了格式化处理,实际返回结果没有进行换行、缩进等格式化处理。

    以下是图片审核增强版-通用基线检测服务同步接口的请求示例,其他接口请参考具体接口文档获取业务入参:

    https://green-cip.cn-shanghai.aliyuncs.com/
        ?Format=JSON
        &Version=2022-03-02
        &Signature=vpEEL0zFHfxXYzSFV0n7%2FZiFL9o%3D
        &SignatureMethod=Hmac-SHA1
        &SignatureNonce=15215528852396
        &SignatureVersion=1.0
        &Action=ImageModeration
        &AccessKeyId=123****cip
        &Timestamp=2022-12-12T12:00:00Z
        &Service=baselineCheck
        &ServiceParameters={"imageUrl": "https://img.alicdn.com/tfs/TB1U4r9AeH2gK0jSZJnXXaT1FXa-2880-480.png",
        "dataId": "img1234567"}

    以下是图片审核增强版-通用基线检测服务同步接口返回参数的JSON代码示例:

    {
        "Msg": "OK",
        "Code": 200,
        "Data": {
            "DataId": "uimg123****",
            "Result": [
                {
                    "Label": "pornographic_adultContent",
                    "Confidence": 81.3
                },
                {
                    "Label": "sexual_partialNudity",
                    "Confidence": 98.9
                }
            ]
        },
        "RequestId": "ABCD1234-1234-1234-1234-1234XYZ"
    }
  • 签名方式

    图片审核增强版服务会对每个访问的请求进行身份验证,因此,需要在请求中包含签名(Signature)信息。图片审核增强版服务通过使用AccessKey IDAccessKey Secret进行对称加密的方法来验证请求的发送者身份。

    AccessKey IDAccessKey Secret由阿里云官方颁发给访问者(可以通过阿里云官方网站申请和管理),其中AccessKey ID用于标识访问者身份;AccessKey Secret是用于加密签名字符串和服务器端验证签名字符串的密钥,必须严格保密,只有阿里云和用户知道。

    用户在访问时,按照下面的方法对请求进行签名处理:

    1. 使用请求参数构造规范化的请求字符串(Canonicalized Query String)。

      1. 按照参数名称的字典顺序对请求中所有的请求参数(包括公共请求参数和给定了的请求接口的自定义参数,但不能包括公共请求参数中提到的Signature参数本身)进行排序。

      2. 对相关请求参数的名称和值进行编码。名称和值要使用UTF-8字符集进行URL编码。

        说明

        一般支持URL编码的库(比如Java中的java.net.URLEncoder)都是按照application/x-www-form-urlencodedMIME类型的规则进行编码的。实现时可以直接使用这类方式进行编码,把编码后的字符串中加号(+)替换成%20、星号(*)替换成%2A、%7E替换回波浪号(~),即可得到上述规则描述的编码字符串。

        URL编码的编码规则如下:

        • 对于字符A-Z、a-z、0-9以及字符中划线(-)、下划线(_)、半角句号(.)、波浪线(~)不编码。

        • 对于其它字符编码成%XY的格式,其中XY是字符对应ASCII码的16进制表示。比如英文的双引号(")对应的编码就是%22

        • 对于扩展的UTF-8字符,编码成%XY%ZA…的格式。

        • 需要说明的是英文空格( )要被编码是%20,而不是加号(+)。

      3. 对编码后的参数名称和值使用英文等号(=)进行连接。

      4. 将英文等号连接得到字符串按参数名称的字典顺序依次使用&符号连接,即得到规范化请求字符串。

    2. 使用a.i构造的规范化字符串按照下面的规则构造用于计算签名的字符串。

      StringToSign=
      HTTPMethod + "&" +
      percentEncode("/") + "&" +
      percentEncode(CanonicalizedQueryString)
      说明

      其中HTTPMethod是提交请求用的HTTP方法,比如POST。percentEncode(/)是按照a.ii中描述的URL编码规则对字符(/)进行编码得到的值,即%2F。percentEncode(CanonicalizedQueryString)是对a.i中构造的规范化请求字符串按a.ii中描述的URL编码规则编码后得到的字符串。

    3. 按照RFC2104的定义,使用上面的用于签名的字符串计算签名HMAC值。

      说明

      注意计算签名时使用的Key就是用户持有的AccessKey Secret并加上一个&字符(ASCII:38),使用的哈希算法是SHA1。

    4. 按照Base64编码规则把上面的HMAC值编码成字符串,即得到签名值(Signature)。

    5. 将得到的签名值作为Signature参数添加到请求参数中,即完成对请求签名的过程。

      说明

      得到的签名值在作为最后的请求参数值提交给内容安全服务器时,要和其他参数一样,按照RFC3986的规则进行URL编码。

如果您在使用过程中出现问题,请加入钉群(钉群号:35573806),联系产品技术专家进行咨询。